[InterviewBit] Array Sum

Array Sum

  • Time :
  • Space :
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
vector<int> Solution::addArrays(vector<int> &A, vector<int> &B) {
reverse(begin(A), end(A));
reverse(begin(B), end(B));
int p = 0, carry = 0;
vector<int> res;
while(p < A.size() and p < B.size()) {
int now = carry + A[p] + B[p];
res.push_back(now % 10);
carry = now / 10;
p += 1;
}
while(p < A.size()) {
int now = carry + A[p];
res.push_back(now % 10);
carry = now / 10;
p += 1;
}
while(p < B.size()) {
int now = carry + B[p];
res.push_back(now % 10);
carry = now / 10;
p += 1;
}

reverse(begin(res), end(res));
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/16/PS/interviewbit/array-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.