forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plus-one.cpp
40 lines (38 loc) · 904 Bytes
/
plus-one.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
// Time: O(n)
// Space: O(1)
// in-place solution
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for (int i = digits.size() - 1; i >= 0; --i) {
if (digits[i] == 9) {
digits[i] = 0;
} else {
++digits[i];
return digits;
}
}
digits[0] = 1;
digits.emplace_back(0);
return digits;
}
};
// Time: O(n)
// Space: O(n)
class Solution2 {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> result(digits.rbegin(), digits.rend());
int carry = 1;
for (auto& num : result) {
num += carry;
carry = num / 10;
num %= 10;
}
if (carry == 1) {
result.emplace_back(carry);
}
reverse(result.begin(), result.end());
return result;
}
};