[LeetCode] Add to Array-Form of Integer

989. Add to Array-Form of Integer

The array-form of an integer num is an array representing its digits in left to right order.

  • For example, for num = 1321, the array form is [1,3,2,1].

Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
for(int i = num.size() - 1; i >= 0 and k; i--) {
int n = k % 10;
k/=10;
num[i] += n;
if(num[i] >= 10) {
num[i] -= 10;
k += 1;
}
}
if(k == 0) return num;

string n = to_string(k);
vector<int> res;
for(auto ch : n)
res.push_back(ch&0b1111);
for(auto digit : num)
res.push_back(digit);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/26/PS/LeetCode/add-to-array-form-of-integer/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.