我一直在嘗試編寫一個計算極大整數的小程序,BigInteger類無法在Java中處理。我的方法是使Integer成爲一個字符串並將其推入堆棧,然後比較兩個堆棧的pop()
並做數學運算和push()
結果。這種方法適用於我的添加,一個addStacks方法,它將兩個Stack作爲參數。就我測試添加大量數據而言,這種方法效果很好。減去兩個整數堆棧的每個節點
int carry = 0;
while(!stackA.empty() && !stackB.empty())
{
try
{
//get the digits to add
int tokenA = stackA.pop();
int tokenB = stackB.pop();
//add them and mod 10
int result = tokenA + tokenB + carry;
int resultDigit = result % 10;
//push the result on to the new stack
resultStack.push(resultDigit);
//the updated carry
carry = result/10;
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}
if (carry > 0)
{
resultStack.push(carry);
}
我的問題是,當我嘗試用減法實現相同的邏輯。在我看來,我認爲兩種行動都是相似的。我的減法方法,兩種方法之間唯一真正的區別是附加代碼,以確保較大的數字總是減去一個較小的數字。我覺得我的方法是關閉的,因爲當我進入100
和10
我得到結果010
哈哈這是非常錯誤的,因爲它應該是90
。有關如何解決我的數學問題的任何提示?
int carry = 0;
while (!stackA.empty() && !stackB.empty())
{
int tempA = 0;
int tempB = 0;
int tokenA = stackA.pop();
int tokenB = stackB.pop();
if (tokenA <= tokenB)
{
tempA = tokenB;
tempB = tokenA;
//System.out.println("StackApop: " + tokenA);
//System.out.println("StackBpop: " + tokenB);
int result = tempA - tempB;
int resultDigit = result % 10;
resultStack.push(resultDigit);
carry = result/10;
}
else if (tokenA >= tokenB)
{
int result = tempA - tempB;
int resultDigit = result % 10;
resultStack.push(resultDigit);
carry = result/10;
}
}
if (carry > 0)
{
resultStack.push(carry);
}
測驗的問題:什麼是最大的數Java的'BigInteger'可以處理? –
@NándorElődFekete:BigIntegers似乎受其字節數組構造函數和toByteArray方法限制,最多爲Integer.MAX_INT字節,或2^31 - 1字節(實際上實際上少一點)。在內部,這些實現可能會產生更大的數字,但他們無法將它們排除。所以最大的數字是大約256^2147483647,其中「^」表示指數,而不是XOR。 –
@JamesKPolk是的,我的測驗問題是讓問題海報思考他是否真的需要進行自定義實現的一種微妙方式,因爲整數2Gbytes的位數仍然是一個相當大的數字。 –