import java.util.;
public class Main {
static int calSumUtil(int a[], int b[],int n, int m){
int[] sum= new int[n];
int i = n - 1, j = m - 1, k = n - 1;
int carry = 0, s = 0;
while (j >= 0){
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
carry = s / 10;
k–;
i–;
j–;
}
while (i >= 0){
s = a[i] + carry;
sum[k] = (s % 10);
carry = s / 10;
i–;
k–;
}
int ans = 0;
if (carry == 1)
ans = 10;
for ( i = 0; i <= n - 1; i++) {
ans =ans+sum[i];
ans =ans10;
}
return ans / 10;
}
static int calSum(int a[], int b[], int n,int m){
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int []a=new int[n];
for(int i=0;i<a.length;i++) {
a[i]=sc.nextInt();
}
int m=sc.nextInt();
int []b=new int[m];
for(int i=0;i<b.length;i++) {
b[i]=sc.nextInt();
}
System.out.print(calSum(a, b, n, m));
System.out.print(“END”);
sc.close();
}
}
here i am getting correct output but my testcases are wrong,why?
Wrong testcases in my solution
how to share on the link
Paste your code on the IDE. Click on save and share the corresponding URL with me
sir can’t you copy and paste the code on your device?
The code isn’t formatted correctly. Half of it is in italics and a few symbols have been ignored. Kindly share the code on online IDE
here is the code import java.util.*;
public class Sumarraycd {
static int calSumUtil(int a[], int b[],int n, int m){
int[] sum= new int[n];
int i = n - 1, j = m - 1, k = n - 1;
int carry = 0, s = 0;
while (j
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
carry = s / 10;
k–;
i–;
j–;
}
while (i >= 0){
s = a[i] + carry;
sum[k] = (s % 10);
carry = s / 10;
i–;
k–;
}
int ans = 0;
if (carry == 1)
ans = 10;
for ( i = 0; i <= n - 1; i++) {
ans += sum[i];
ans *= 10;
}
return ans / 10;
}
static int calSum(int a[], int b[], int n,int m){
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int []a=new int[n];
for(int i=0;i<a.length;i++) {
a[i]=sc.nextInt();
}
int m=sc.nextInt();
int []b=new int[m];
for(int i=0;i<b.length;i++) {
b[i]=sc.nextInt();
}
System.out.println(calSum(a, b, n, m));
sc.close();
}
}
You have assumed that n is always greater than m which is incorrect.
Example: if the input arrays are
[1,2]
[4,5,6]
You need to consider the case where n is smaller than n.
Also, your output pattern doesn’t matches with the expected output.
For the input
4
1 0 2 9
5
3 4 5 6 7
You need to output the pattern in this format:
3, 5, 5, 9, 6, END
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.