我一直在尝试编写一个计算极大整数的小程序,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的位数仍然是一个相当大的数字。 –