Skip to content

Commit 2446a5e

Browse files
authored
Sum of Two Arrays Solution Added
1 parent 06c2521 commit 2446a5e

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Hacker Blocks/Sum of Two Arrays.cpp

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/* Hacker Blocks */
2+
/* Title - Sum of Two Arrays */
3+
// Take as input N, the size of array. Take N more inputs and store that in an array. Take as input M, the size of second array and take M more inputs and store that in second array. Write a function that returns the sum of two arrays. Print the value returned.
4+
5+
// Input Format
6+
// Constraints
7+
// Length of Array should be between 1 and 1000.
8+
9+
// Output Format
10+
// Sample Input
11+
// 4
12+
// 1 0 2 9
13+
// 5
14+
// 3 4 5 6 7
15+
// Sample Output
16+
// 3, 5, 5, 9, 6, END
17+
// Explanation
18+
// 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 ) .
19+
20+
#include<iostream>
21+
using namespace std;
22+
23+
int main() {
24+
int n,m;
25+
cin>>n;
26+
int a[n];
27+
for(int i=0;i<n;i++)
28+
cin>>a[i];
29+
cin>>m;
30+
int b[m];
31+
for(int i=0;i<m;i++)
32+
cin>>b[i];
33+
int k = max(n,m)+1;
34+
int c[k],carry=0;
35+
int i = n-1,p;
36+
int j = m-1;
37+
for(p=k-1;p>=0;p--){
38+
if(i>=0 && j>=0){
39+
c[p] = (a[i]+b[j]+carry)%10;
40+
carry = (a[i]+b[j]+carry)/10;
41+
i--;
42+
j--;
43+
}
44+
else
45+
break;
46+
}
47+
while(i>=0)
48+
{
49+
c[p--] = (a[i] + carry)%10;
50+
carry = (a[i]+carry)/10;
51+
i--;
52+
}
53+
while(j>=0)
54+
{
55+
c[p--] = (b[j] + carry)%10;
56+
carry = (b[j]+carry)/10;
57+
j--;
58+
}
59+
if(carry>0){
60+
c[0]=carry;
61+
p=0;
62+
}
63+
else p=1;
64+
for(;p<k;p++)
65+
cout<<c[p]<<", ";
66+
cout<<"END";
67+
return 0;
68+
}

0 commit comments

Comments
 (0)