In this question, I need to find the sum of 2 arrays element by element. Arrays can be of unequal length.
Explanation: Sum of [1, 0, 2, 9] and [3, 4, 5, 6, 7] is [3, 5, 5, 9, 6] and the first digit represents carry over , if any (0 here ).
Here's what I could come up with. Let me know if anything could be done better,or anything i did wrong.
Also earlier someone suggested me that I should split my code into smaller pieces that are easier to read and test individually. Perhaps if anyone could help with the method signatures that I should make(if any).
private static void sum(int[] arr1, int[] arr2) {
ArrayList<Integer> arraySum = new ArrayList<>();
int[] largerArray, smallerArray;
boolean flag;
if (arr1.length == arr2.length) {
largerArray = arr1;
smallerArray = arr2;
flag = true;
} else if (arr1.length > arr2.length) {
largerArray = arr1;
smallerArray = arr2;
flag = false;
} else {
largerArray = arr2;
smallerArray = arr1;
flag = false;
}
int sum = 0, carry = 0;
int diff = largerArray.length - smallerArray.length;
for (int i = smallerArray.length - 1; i >= 0; i--) { //traverse through smaller array
sum = largerArray[i + diff] + smallerArray[i] + carry;
carry = 0;
if (sum > 9) {
int N = sum;
while (N != 0) {
int rem = N % 10;
if (N < 10) {
carry = rem;
} else {
arraySum.add(rem);
}
if (i == 0 && carry != 0 && flag) { //if we are at last element & carry!=0 add carry as first digit
arraySum.add(carry);
}
N = N / 10;
}
} else {
arraySum.add(sum);
}
}
if (!flag) {
for (int i = diff - 1; i >= 0; i--) { // now sum remaining elements of larger array
sum = arr1[i] + carry;
carry = 0;
if (sum > 9) {
int N = sum;
while (N != 0) {
int rem = N % 10;
if (N < 10) {
carry = rem;
} else {
arraySum.add(rem);
}
if (i == 0 && carry != 0) { //if we are at last element & carry!=0 add carry as first digit
arraySum.add(carry);
}
N = N / 10;
}
} else {
arraySum.add(sum);
}
}
}
display(arraySum);
}
Refactor
from the context menu? \$\endgroup\$