-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_to_array_form.cpp
76 lines (69 loc) · 1.58 KB
/
add_to_array_form.cpp
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
/*
* =====================================================================================
*
* Filename: add_to_array_form.cpp
*
* Description: 989. Add to Array-Form of Integer.
* https://leetcode.com/problems/add-to-array-form-of-integer/
*
* Version: 1.0
* Created: 01/31/2023 21:38:20
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <cstdio>
#include <vector>
using std::vector;
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> arr;
if (num.size() < 10) {
arr.resize(11);
} else {
arr.resize(num.size() + 1);
}
auto fit = [&](const int i) {
if ((i + 1 < arr.size()) && arr[i + 1] > 9) {
arr[i + 1] -= 10;
arr[i] += 1;
}
};
int i = arr.size() - 1;
int j = num.size() - 1;
while (j >= 0 && k > 0) {
arr[i--] = num[j--] + (k % 10);
fit(i + 1);
k /= 10;
}
while (j >= 0) {
arr[i--] = num[j--];
fit(i + 1);
}
while (k > 0) {
arr[i--] = k % 10;
fit(i + 1);
k /= 10;
}
fit(i);
if (arr[i] == 0) {
i++;
}
return vector<int>(arr.begin() + i, arr.end());
}
};
int main(int argc, char* argv[]) {
vector<int> num = {2, 1, 5};
int k = 806;
vector<int> arr = Solution().addToArrayForm(num, k);
for (const int n : arr) {
printf("%d ", n);
}
printf("\n");
return 0;
}