Problem
66. Plus One
Logic
- Iterate backwards starting from the last digit (least significant digit).
- If the current digit is less than
9, increment it by 1 and return digits immediately since no carry propagation is needed.
- If the current digit is
9, set it to 0 and continue the loop to carry 1 over to the left.
- If all digits were
9 (e.g. [9, 9]), the loop completes with all digits set to 0. Inserting 1 at the beginning of digits handles the overflow carry ([1, 0, 0]).
Code
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for (int i = digits.size() - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
digits.insert(digits.begin(), 1);
return digits;
}
};