-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAdd One To Number.cpp
More file actions
63 lines (39 loc) · 1008 Bytes
/
Add One To Number.cpp
File metadata and controls
63 lines (39 loc) · 1008 Bytes
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
vector<int> Solution::plusOne(vector<int> &A) {
// int no = 0,in=1;
// for(int i =A.size()-1;i>=0;i--){
// no = no+(in*A[i]);
// in*=10;
// }
// no+=1;
// vector<int> v;
// while(no){
// v.push_back(no%10);
// no/=10;
// }
// reverse(v.begin(),v.end());
// return v;
while(!A.empty() && A[0]==0){
A.erase(A.begin());
}
if(A.empty()){
A.push_back(0);
}
int n = A.size();
if(A[n-1]<9){
A[n-1]++;
}else{
int cr = (A[n-1]+1)/10;
A[n-1] = (A[n-1]+1)%10;
int x = n-2;
while(cr && x>=0){
int y = A[x];
A[x] = (A[x]+cr)%10;
cr = (y+cr)/10;
x--;
}
if(cr==1){
A.insert(A.begin(),1);
}
}
return A;
}