-
Notifications
You must be signed in to change notification settings - Fork 0
/
Addition ot two array.txt
101 lines (58 loc) · 2.23 KB
/
Addition ot two array.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
Problem Statement
You are given two numbers 'A' and 'B' in the form of two arrays (A[] and B[]) of lengths 'N' and 'M' respectively, where each array element represents a digit. You need to find the sum of these two numbers and return this sum in the form of an array.
Note:
1. The length of each array is greater than zero.
2. The first index of each array is the most significant digit of the number. For example, if the array A[] = {4, 5, 1}, then the integer represented by this array is 451 and array B[] = {3, 4, 5} so the sum will be 451 + 345 = 796. So you need to return {7, 9, 6}.
3. Both numbers do not have any leading zeros in them. And subsequently, the sum should not contain any leading zeros.
Input Format:
The first line of the input contains an integer T, denoting the number of test cases.
The first line of each test case contains two space-separated integers 'N' and 'M', denoting the size of the two arrays.
The second line of each test case contains 'N' space-separated integers denoting the elements of the first array.
The third line of each test case contains 'M' space-separated integers denoting the elements of the second array.
Output Format:
The only line of output of each test case contains space-separated digits which correspond to the sum of the two numbers 'A' and 'B'.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10^2
1 <= N, M <= 10^4
0 <= A[i], B[i] <= 9
Time Limit: 1 sec
Sample Input 1:
vector<int> findArraySum(vector<int>&a, int n, vector<int>&b, int m)
{
vector<int> ans;
int carry=0;
int sum=0;
int i=n-1;
int j=m-1;
while(i>=0 && j>=0)
{
sum = a[i] + b[j] + carry;
carry = sum/10;
sum=sum%10;
ans.push_back(sum);
i--;j--;
}
while(i>=0){
sum=a[i]+carry;
carry=sum/10;
sum=sum%10;
ans.push_back(sum);
i--;
}
while(j>=0){
sum=b[j]+carry;
carry=sum/10;
sum=sum%10;
ans.push_back(sum);
j--;
}
while(carry>0){
sum=carry;
ans.push_back(sum);
carry=0;
}
reverse(ans.begin(),ans.end());
return ans;
}