-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_66_PlusOne.cpp
60 lines (43 loc) · 1.13 KB
/
LC_66_PlusOne.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
/*
https://leetcode.com/problems/plus-one/
66. Plus One
https://practice.geeksforgeeks.org/problems/plus-one/1/
*/
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
unsigned int carry=0;
digits[n-1] += 1;
for(int j=n-1; j>=0; j--)
{
digits[j] += carry;
if(digits[j]<10)
{
carry=0;
break;
}
digits[j] %= 10;
carry = 1;
}
if(carry)
digits.insert(digits.begin(), 1);
return digits;
}
vector<int> plusOne_1(vector<int>& digits) {
int n = digits.size();
int sum=0, carry=1;
vector<int> ans;
for(int j=n-1; j>=0; j--)
{
sum = carry;
sum += digits[j];
carry = sum/10;
ans.push_back(sum%10);
}
if(carry)
ans.push_back(carry);
reverse(ans.begin(), ans.end());
return ans;
}
};