-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path66.PlusOne.cpp
32 lines (29 loc) · 873 Bytes
/
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
#include <vector>
class Solution {
public:
std::vector<int> plusOne(std::vector<int>& digits) {
// iterate from the last element to the first one
// and pass the carry to the higher (to the left) position if needed.
int i = digits.size() - 1; // last element
while (i > 0) {
if(digits[i] + 1 < 10) {
digits[i]++;
return digits;
} else { // carry case
digits[i] = 0;
}
i--;
}
// edge case (new element needed)
if (i == 0) {
if(digits[i] + 1 < 10) {
digits[i]++;
return digits;
} else { // carry case
digits[i] = 0;
}
digits.insert(digits.begin(), 1); // inserting carry
}
return digits;
}
};