I'm still learning to program and i'm trying to add two arrays, A and B, while keeping track of carry. The arrays are all of SIZE = 20
and look like this: A = {0,0,..,n}
My code below does not seem to work and I cannot for the life of me find out what the error is. For example, if I add A ={0,0,0...,1,2,3}
as an array and B ={0,0,0,...,7,8,9}
as an array I get 802
instead of 912.
Code:
我还在学习编程,我正在尝试添加两个数组A和B,同时跟踪进位。这些数组都是SIZE = 20,看起来像这样:A = {0,0,..,n}我的代码似乎不起作用,我不能在我的生活中找出错误是什么。例如,如果我将A = {0,0,0 ...,1,2,3}添加为数组,并将B = {0,0,0,...,7,8,9}添加为数组我得到802而不是912.代码:
int index = SIZE -1;
int[] newBI = new int[SIZE]
while(index >=0)
{
int carry = 0;
int sum = A[index] + B[index] + carry;
if(sum >=10) {
carry = sum/10;
sum = sum %10;
}
newBI[index] = sum;
index--;
}
return newBI;
}
Please help!
1 个解决方案
#1
2
As has been noted in the comments, you need to remember the value of carry
from one digit to the next. Also, it's important to clear the carry
when there's no digit overflow. Finally, if carry
is set when the loop ends then the sum is too large to fit in the array.
正如评论中所指出的,您需要记住从一位数到下一位数的进位值。此外,在没有数字溢出的情况下清除进位非常重要。最后,如果在循环结束时设置了进位,则总和太大而无法放入数组中。
static int[] sum(int[] A, int[] B)
{
int index = SIZE -1;
int[] newBI = new int[SIZE];
int carry = 0;
while(index >=0)
{
int sum = A[index] + B[index] + carry;
if(sum >= 10) {
carry = sum/10;
sum = sum %10;
}
else
{
// important to clear the carry
carry = 0;
}
newBI[index] = sum;
index--;
}
if(carry == 1)
{
throw new ArithmeticException();
}
return newBI;
}
#1
2
As has been noted in the comments, you need to remember the value of carry
from one digit to the next. Also, it's important to clear the carry
when there's no digit overflow. Finally, if carry
is set when the loop ends then the sum is too large to fit in the array.
正如评论中所指出的,您需要记住从一位数到下一位数的进位值。此外,在没有数字溢出的情况下清除进位非常重要。最后,如果在循环结束时设置了进位,则总和太大而无法放入数组中。
static int[] sum(int[] A, int[] B)
{
int index = SIZE -1;
int[] newBI = new int[SIZE];
int carry = 0;
while(index >=0)
{
int sum = A[index] + B[index] + carry;
if(sum >= 10) {
carry = sum/10;
sum = sum %10;
}
else
{
// important to clear the carry
carry = 0;
}
newBI[index] = sum;
index--;
}
if(carry == 1)
{
throw new ArithmeticException();
}
return newBI;
}