forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd to Array-Form of Integer.cpp
48 lines (45 loc) · 1008 Bytes
/
Add to Array-Form of Integer.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
Time: O(max(n,Log k)) Space: O(1)
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> res;
int i=size(num)-1;
int c=0,sum;
while(i>=0){
sum=num[i]+k%10+c;
res.push_back(sum%10);
c=sum/10;
k/=10;i--;
}
while(k){
sum=k%10+c;
res.push_back(sum%10);
c=sum/10;
k/=10;
}
if(c)
res.push_back(c);
reverse(begin(res),end(res));
return res;
}
};
--> Approach 2
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> res;
int i=size(num)-1;
int sum;
while(i>=0){
sum=num[i]+k;
res.push_back(sum%10);
k=sum/10;i--;
}
while(k){
res.push_back(k%10);
k/=10;
}
reverse(begin(res),end(res));
return res;
}
};