为了练习,我试图通过将它们放在数组中并在数组中添加相应的元素来添加两个非常长的整数。但是,当尝试添加结转时,我遇到了问题(即,结转是 1,例如,当您执行 199 + 199 = 398 时,您添加到十位)。
当做 167 + 189 时,我得到了正确的答案,即 356。但是,对于这个例子(199 + 199),我得到的是 288 而不是 398。我的问题是,为什么我做的时候会得到一个不正确的答案199 + 199,如果我做 167 + 189 时结转效果很好?
if (stringNumOneLength == stringNumTwoLength)
{ int answer;
int carryOver = 0;
int answerArray[] = new int[stringNumOneLength + 1];
for (int i = 1; i <= stringNumTwoLength; i = i + 1)
{
answer = Character.getNumericValue(stringNumOne.charAt(stringNumOneLength - i)) + Character.getNumericValue(stringNumTwo.charAt(stringNumTwoLength - i) + carryOver);
System.out.println(answer);
if (answer >= 10)
{
for (int j = 0; j <= 9; j = j + 1)
{
if (10 + j == answer)
{
carryOver = 1;
answer = j;
System.out.println("The carryover is " + carryOver + ".");
}
}
}
else
{
carryOver = 0;
}
answerArray[stringNumOneLength + 1 - i] = answer;
}
System.out.println(Arrays.toString(answerArray));
}
输出如下:
[1, 9, 9]
[1, 9, 9]
18
结转为 1。
8
2
[0, 2, 8, 8]