Skip to content

Commit cc57124

Browse files
authored
Add files via upload
1 parent 29089de commit cc57124

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
//Sum of two different arrays, arr1 and arr2, of size n and m respectively, where both the arrays contain single digits at each index.
2+
//For example, given two arrays, each of size 3, arr1 = 6 2 6, arr2 = 6 5 4, the output would be 1 2 8 0
3+
/*Test case:
4+
5+
Input:
6+
2
7+
3
8+
1 5 2
9+
2
10+
1 3
11+
4
12+
9 7 1 2
13+
3
14+
5 8 8
15+
16+
Output:
17+
0 1 6 5
18+
1 0 3 0 0
19+
20+
*/
21+
22+
#include <iostream>
23+
using namespace std;
24+
25+
void sumOfTwoArrays(int *arr1, int m, int *arr2, int n, int *output)
26+
{
27+
int i = m-1, j = n-1, k = m, carry = 0, number = 0;
28+
if(m >= n) {
29+
k = m;
30+
while(i >= 0) {
31+
number = carry;
32+
if(j >= 0)
33+
number = number + arr2[j];
34+
number = arr1[i] + number;
35+
output[k] = number%10;
36+
carry = number/10;
37+
j--;
38+
i--;
39+
k--;
40+
}
41+
output[k] = carry;
42+
43+
}
44+
else {
45+
k = n;
46+
while(j >= 0) {
47+
number = arr2[j] + carry;
48+
if(i >= 0)
49+
number = number + arr1[i];
50+
output[k] = number%10;
51+
carry = number/10;
52+
i--;
53+
j--;
54+
k--;
55+
}
56+
output[k] = carry;
57+
}
58+
}
59+
60+
int main()
61+
{
62+
int t;
63+
cin >> t;
64+
65+
while (t--)
66+
{
67+
int m;
68+
cin >> m;
69+
int *arr1 = new int[m];
70+
for (int i = 0; i < m; i++) {
71+
cin >> arr1[i];
72+
}
73+
int n;
74+
cin >> n;
75+
int *arr2 = new int[n];
76+
for (int i = 0; i < n; i++) {
77+
cin >> arr2[i];
78+
}
79+
80+
int output_size = 1 + max(m, n);
81+
82+
int *output = new int[output_size];
83+
84+
sumOfTwoArrays(arr1, m, arr2, n, output);
85+
86+
for (int i = 0; i < output_size; ++i)
87+
{
88+
cout << output[i] << " ";
89+
}
90+
cout << endl;
91+
delete[] arr1;
92+
delete[] arr2;
93+
delete[] output;
94+
}
95+
96+
return 0;
97+
}

0 commit comments

Comments
 (0)