对于练习,我试图通过将它们放在数组中并在数组中添加相应的元素来添加两个非常长的整数。然而,当试图添加结转时,我遇到了问题(即,结转为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]
答案 0 :(得分:2)
您正在将角色添加到角色而不是其值:
... + Character.getNumericValue(stringNumTwo.charAt(stringNumTwoLength - i) + carryOver);
您想在+。
中移动右父注意你的for循环是不必要的。这也是做同样的事情:
if (answer >= 10)
{
answer -= 10;
carryOver = 1;
System.out.println("The carryover is 1.");
}
else ...
如果您对惯用解决方案感兴趣:
public class Test {
public String add(String a, String b) {
StringBuilder r = new StringBuilder();
int carry = 0;
for (int ia = a.length() - 1, ib = b.length() - 1; ia >= 0 || ib >= 0; ia--, ib--) {
int aDigit = ia < 0 ? 0 : Character.getNumericValue(a.charAt(ia));
int bDigit = ib < 0 ? 0 : Character.getNumericValue(b.charAt(ib));
int sum = carry + aDigit + bDigit;
if (sum >= 10) {
sum -= 10;
carry = 1;
}
else {
carry = 0;
}
r.append(Character.forDigit(sum, 10));
}
if (carry > 0) {
r.append('1');
}
return r.reverse().toString();
}
public void run() {
System.out.println("789 + 89 = " + add("789", "89"));
System.out.println("12 + 128 = " + add("12", "128"));
System.out.println("999 + 999 = " + add("999", "999"));
}
public static void main(String[] args) {
new Test().run();
}
}
答案 1 :(得分:1)
这一行的括号:
answer = Character.getNumericValue(stringNumOne.charAt(stringNumOneLength - i)) + Character.getNumericValue(stringNumTwo.charAt(stringNumTwoLength - i) + carryOver);
错了。注意+ carryOver
如何在对Character.getNumericValue的调用中。