I am looking to take two arrays of Integers and add them together, but I am having some difficulty with the carrying bit.
public static int [] add(int [] a, int [] b)
{
int col = 0;
int carry = 0;
int[] totalArray = new int[MAX_DIGITS + 1];
for(int i = MAX_DIGITS - 1; i > 0; i--) {
col = a[i] + b[i] + carry;
if(col >= 10) {
carry = col / 10;
totalArray[i] %= 10;
} else {
totalArray[i] = col;
carry = 0;
}
}
totalArray[0] = carry;
return totalArray;
}
The above code adds 204 + 435 correctly but fails to add 22 + 3122 + 12 correctly (ouputs 65). I have written other methods to make sure all of the digits are properly indexed within the array and have tested those methods. Seeing as it works for 204 + 435 but not the other, I can't see what's tripping me up. I do not want to use the BigInteger class - before anyone suggests I should.
Given int[]a [0000000000000000000000999] and int[]b [0000000000000000000000483] currently add(a,b) returns [0000000000000000000001000]
This works just fine. Just make certain that all your arrays only occupy locations 1 thru MAX_DIGITS-1
with actual values. This allows for carries into totalArray[0]
.
static int MAX_DIGITS = 6;
int[] a = {0,0,0,0,2,2};
int [] b = {0,0,3,1,2,2};
int [] c = {0,0,0,0,1,2};
int[] part1 = add(a,b);
int [] total = add(part1, c);
System.out.println(Arrays.toString(total));
Prints
[0, 0, 3, 1, 5, 6]
totalArray
array to MAX_DIGITS
i > 0
to i >= 0
in the loop.index 0
was 0
in all the arrays.public static int[] add(int[] a, int[] b) {
int col = 0;
int carry = 0;
int[] totalArray = new int[MAX_DIGITS];
for (int i = MAX_DIGITS-1; i >= 0; i--) {
col = a[i] + b[i] + carry;
if (col >= 10) {
carry = col / 10;
totalArray[i] %= 10;
} else {
totalArray[i] = col;
carry = 0;
}
}
totalArray[0] = carry;
return totalArray;
}