66. Plus One
Problem
digits holds a non-negative integer, most significant digit first, without leading zeros. Add one and return the resulting digits.
Example: [1,2,3] → [1,2,4]; [9,9] → [1,0,0]
Walk from the last digit: a 9 becomes 0 and carries; any other digit increments and we're done. All 9s → prepend 1.
Complexity: O(n).
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
for i in range(len(digits) - 1, -1, -1):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
return [1] + digits
assert Solution().plusOne([1, 2, 3]) == [1, 2, 4]
assert Solution().plusOne([9, 9]) == [1, 0, 0]
class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) { digits[i]++; return digits; }
digits[i] = 0;
}
int[] res = new int[digits.length + 1];
res[0] = 1;
return res;
}
}
func plusOne(digits []int) []int {
for i := len(digits) - 1; i >= 0; i-- {
if digits[i] < 9 {
digits[i]++
return digits
}
digits[i] = 0 // 9 + 1: carry on
}
return append([]int{1}, digits...)
}