two test case are not passing please check my code
Arrays-Sum Of Two Arrays
Hello @sk3657860,
Your code is failing for the test cases like:
-
Example 1:
5
3 4 5 6 7
5
9 1 0 2 9
Expected Output:
1, 2, 5, 5, 9, 6, END
Your Output:
2, 5, 5, 9, 6, END -
Example 2:
Example:
3
4 2 3
4
9 8 7 6
Expected Output:
1, 0, 2, 9, 9, END
Your Output:
0, 2, 9, 9, END
Explanation:
In both the cases your code is not accounting for the carry generated in the leftmost addition.
Hope, this would help.
Give a like, if you are satisfied.
still one test case is not passing
#include
#include
using namespace std;
int* arraysum(intarr1, intarr2,int n1, int n2,int* output){
int i=n1-1,j=n2-1;
int carry=0;
int p;
(arr1[0]+arr2[0]>=9)? p=max(n1,n2): p=max(n1,n2)-1;
while(i>=0 || j>=0){
if(j<0){
int sum=arr1[i]+carry;
carry=sum/10;
output[pā]=sum%10;
}
if(i<0){
int sum=arr2[j]+carry;
carry=sum/10;
output[pā]=sum%10;
}
if(i>=0 && j>=0){
int sum=(arr1[i]+arr2[j])+carry;
carry=sum/10;
output[pā]=sum%10;
}
iā;
jā;
}
if( arr1[0]+arr2[0]>=9){
output[p]=carry;
}
}
int main() {
int n1,n2;
cin>>n1;
intarr1=new int[n1];
for(int i=0;i<n1;i++){
cin>>arr1[i];
}
cin>>n2;
intarr2=new int[n2];
for(int i=0;i<n2;i++){
cin>>arr2[i];
}
int *output=new int[max(n1,n2)];
arraysum(arr1,arr2,n1,n2,output);
int k=arr1[0]+arr2[0]>=9?max(n1,n2):max(n1,n2)-1;
for(int i=0;i<=k;i++){
cout<<output[i]<<", ";
}
cout<<"END"<<endl;
delete [] arr1;
delete [] arr2;
delete [] output;
return 0;
}
Hey @sk3657860,
Always share code using online coding blocks ide.
The way you have shared it has introduced many syntax error to it.
Test your code for the following code:
1
1
1
1
Expected Output:
2, END
If your code runs correctly on above, share your code with me on https://ide.codingblocks.com/
yes its working
here is my code
Hey @sk3657860,
The logic (arr1[0]+arr2[0]>=9)? p=max(n1,n2): p=max(n1,n2)-1; would not work for the case:
When the arrays are of varied length.
Example:
3
1 2 3
4
9 8 7 6
Your Output:
0, 9, 9, 9, 9, END
Expected Output:
9, 9, 9, 9, END
Hope, this would help.