-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path989.cpp
More file actions
74 lines (73 loc) · 1.91 KB
/
989.cpp
File metadata and controls
74 lines (73 loc) · 1.91 KB
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
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> kNum;
while (k) {
kNum.push_back(k % 10);
k /= 10;
}
reverse(num.begin(), num.end());
int numIdx = 0;
int kNumIdx = 0;
int carry = 0;
vector<int> res;
while (numIdx < num.size() && kNumIdx < kNum.size()) {
carry = carry + kNum[kNumIdx] + num[numIdx];
res.push_back(carry % 10);
carry /= 10;
kNumIdx++;
numIdx++;
}
while (numIdx < num.size()) {
carry = carry + num[numIdx];
res.push_back(carry % 10);
carry /= 10;
numIdx++;
}
while (kNumIdx < kNum.size()) {
carry = carry + kNum[kNumIdx];
res.push_back(carry % 10);
carry /= 10;
kNumIdx++;
}
if (carry) {
res.push_back(carry % 10);
}
reverse(res.begin(), res.end());
return res;
}
};
// v2
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> kNum;
while (k) {
kNum.push_back(k % 10);
k /= 10;
}
reverse(num.begin(), num.end());
int numIdx = 0;
int kNumIdx = 0;
int carry = 0;
vector<int> res;
while (numIdx < num.size() || kNumIdx < kNum.size()) {
if (numIdx < num.size()) {
carry += num[numIdx];
numIdx++;
}
if (kNumIdx < kNum.size()) {
carry += kNum[kNumIdx];
kNumIdx++;
}
res.push_back(carry % 10);
carry /= 10;
}
while (carry) {
res.push_back(carry % 10);
carry /= 10;
}
reverse(res.begin(), res.end());
return res;
}
};