2016-03-04 48 views
0

我一直在嘗試編寫一個計算極大整數的小程序,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); 
      } 

我的問題是,當我嘗試用減法實現相同的邏輯。在我看來,我認爲兩種行動都是相似的。我的減法方法,兩種方法之間唯一真正的區別是附加代碼,以確保較大的數字總是減去一個較小的數字。我覺得我的方法是關閉的,因爲當我進入10010我得到結果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); 
     } 
+0

測驗的問題:什麼是最大的數Java的'BigInteger'可以處理? –

+0

@NándorElődFekete:BigIntegers似乎受其字節數組構造函數和toByteArray方法限制,最多爲Integer.MAX_INT字節,或2^31 - 1字節(實際上實際上少一點)。在內部,這些實現可能會產生更大的數字,但他們無法將它們排除。所以最大的數字是大約256^2147483647,其中「^」表示指數,而不是XOR。 –

+0

@JamesKPolk是的,我的測驗問題是讓問題海報思考他是否真的需要進行自定義實現的一種微妙方式,因爲整數2Gbytes的位數仍然是一個相當大的數字。 –

回答

0

我會重命名爲借入。

  int result = tempA - tempB - carry; 
      carry = result < 0 ? 1 : 0; 
      result += 10*carry; 
      int resultDigit = result % 10; 

      resultStack.push(resultDigit); 


    if (carry > 0) 
    { 
     resultStack.push(10 - carry); // Negative number actually 
    } 

BigInteger很聰明,你可能想看看來源。


當減去兩個數字,它可能是在先前步驟中一個數位已被減少一個,以在先前步驟中添加10。

當減去並得到一個否定結果時,加十,並且從以下步驟中減去1。

(使用模%需要注意負數,結果可能是負面的。)

+0

我知道BigInteger類會有幫助,它不是它不適合我所要做的,我只是有意嘗試去做而不使用那個java類。你能解釋一下這裏的一些代碼嗎?我試着實現它,並越來越近。 – wonderBoy322

+0

增加了解釋,並且我理解這個願望 - 儘管存在BigInteger - 嘗試自己做一次。但其他訪問者應該指向BigInteger。 –