Plus One
You're given a non-empty array digits that represents a non-negative integer, most significant digit first. There are no leading zeros, except in the number 0 itself. Add one to the integer and return the resulting digits in the same form.
Examples
digits = [4,0,7] returns [4,0,8]
407 + 1 = 408. There is no carry, so only the last digit changes.
digits = [2,9,9] returns [3,0,0]
The trailing nines turn into zeros, and the carry stops at the 2.
digits = [9,9,9] returns [1,0,0,0]
Every digit is 9, so the result needs one more digit than the input.
Constraints
- 1 <= digits.length <= 100
- 0 <= digits[i] <= 9
- digits has no leading zeros, except in the number 0 itself.
Hints
When you add one by hand, which digits can change?
Only a trailing run of nines changes besides the last digit: each 9 becomes 0 and passes the carry left. The first digit that isn't 9 absorbs it.
Loop i from n - 1 down to 0. If digits[i] < 9, increment it and return. Otherwise set it to 0. If the loop finishes, return a new array with 1 followed by n zeros.
Drill This: Your Approach First
Approach
Walk from the last digit toward the front. If the digit is less than 9, increment it and return right away, since nothing carries further. Otherwise it is a 9: set it to 0 and keep moving left with the carry. If the loop passes the first digit, every digit was 9, so return a new array of length n + 1 with a 1 followed by zeros. O(n) time, and O(1) extra space except in the all-nines case.
Time
O(n)
Space
O(1), or O(n) when every digit is 9
Pitfall
Solutions
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[] out = new int[digits.length + 1];
out[0] = 1;
return out;
}
}class Solution:
def plusOne(self, digits):
for i in range(len(digits) - 1, -1, -1):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
return [1] + digits