Hey can you please review my code and tell me where it is failing??
Also my approach seems like naive and involves many loops and creating new arrays , can you suggest something better , I really can’t think of something else as of now
2 test case failing
I’m really sorry I acknowledged the doubt and forgot to reply. Anyways, can you please post your code as well.
package Arrays;
import java.util.Scanner;
public class SumOfTwoArrays {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] arr1 = new int[N];
for (int i = 0; i < N; i++) {
arr1[i] = scanner.nextInt();
}
int M = scanner.nextInt();
int[] arr2 = new int[M];
for (int i = 0; i < M; i++) {
arr2[i] = scanner.nextInt();
}
int l1 = arr1.length;
int l2 = arr2.length;
if (l1 == l2) {
//sum
printSum(arr1,arr2);
} else if (l1 > l2) {
int diff = l1 - l2;
int[] arr3 = new int[l1];
for (int i = 0; i < l1; i++) {
if (i < diff) {
arr3[0] = 0;
} else {
arr3[i] = arr2[i - diff];
}
}
printSum(arr1,arr3);
} else {
int diff = l2 - l1;
int[] arr3 = new int[l2];
for (int i = 0; i < l2; i++) {
if (i < diff) {
arr3[0] = 0;
} else {
arr3[i] = arr1[i - diff];
}
}
printSum(arr3,arr2);
}
}
public static void printSum(int[] arr1, int[] arr2) {
int length = arr1.length;
int[] result = new int[length + 1];
for (int i = length - 1; i >= 0; i--) {
int sum = arr1[i] + arr2[i] + result[i+1];
if (sum > 9) {
result[i] += 1;
result[i+1] += sum-10;
}else {
result[i+1] = sum;
}
}
for(int i =0;i<result.length;i++){
if(i==0 && result[i]==0){
continue;
}else {
System.out.print(result[i] + ", ");
}
}
System.out.println("END");
}
}
Did you see it?? Please review
You have made a simple solution really complex. Don’t think about the cases comparing their lengths. Simply think how do you add 2 numbers with different number of digits in them. You have to apply the same procedure. Start from i = l1 - 1 & j = l2 - 1 & carry = 0, now keep a variable sum = 0. if i >= 0 , add A[i] to sum, if j >= 0 add B[j] to sum & then add carry. Now if this sum equals 0 exit, else, make carry = sum / 10 and set thi digit in answer to sum % 10;
I didn’t quite understand the explanation actually could you explain in a more detailed way , sorry for the trouble.
Also if we just doing addition of nos then there is no use of arrays , I can just add 2 nos and I will get the answer?
got it , thanks! …