LeetCode 989. Add to Array-Form of Integer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<int> addToArrayForm(vector<int> &A, int K) {
const int n = A.size();
vector<int> ans;
for (int i = n - 1; i >= 0; --i) {
int sum = A[i] + K % 10;
K /= 10;
if (sum >= 10) {
K++;
sum -= 10;
}
ans.push_back(sum);
}
for (; K > 0; K /= 10)
ans.push_back(K % 10);
reverse(ans.begin(), ans.end());
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<int> addToArrayForm(vector<int> &A, int K) {
const int n = A.size();
vector<int> ans;
for (int i = n - 1; i >= 0 || K > 0; --i, K /= 10) {
if (i >= 0)
K += A[i];
ans.push_back(K % 10);
}
reverse(ans.begin(), ans.end());
return ans;
}
};