2016-03-04 46 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。 –