Plus One
You are given a large integer represented as an array of digits, where each element is a single digit and the most significant digit is first. Increment the large integer by one and return the resulting array of digits. Walk the digits from right to left , adding the carry as you go — most additions only affect the last digit, and a carry only ripples further left when a digit rolls over from 9 to 0.
Constraints
- 1 ≤ digits.length ≤ 100
- 0 ≤ digitsi ≤ 9
- digits does not contain leading zeros, except the number 0 itself
Example
digits = [1, 2, 3][1, 2, 4]Explanation The array represents 123, incrementing gives 124.
In plain terms
- Carry
- The extra 1 that spills over into the next digit to the left when a digit adds up to 10 or more, just like carrying a digit in long addition by hand.
Add one from the rightmost digit, carrying left as needed
i=2 (value 3). Add 1 -> 4, which is less than 10 — done, no carry.
What happens in this step
i = 2 (value 3) digits[i] + 1 = 4 4 is less than 10, so write 4 and stop — no carry needed.
Steps to visualize
- Start at the last digit of the array.
- Add one to that digit.
- If the digit is now 10, set it to 0 and move one step left to carry the extra 1.
- If the digit is less than 10, stop — no more carrying is needed.
- If the carry runs past the first digit, insert a new 1 at the front.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
i=2 (value 3). Add 1 -> 4, which is less than 10 — done, no carry.
What happens in this step
i = 2 (value 3) digits[i] + 1 = 4 4 is less than 10, so write 4 and stop — no carry needed.
Solution
function plusOne(digits) {
const result = digits.slice();
for (let i = result.length - 1; i >= 0; i--) {
if (result[i] < 9) {
result[i]++;
return result;
}
result[i] = 0;
}
return [1, ...result];
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
digits = [1, 2, 3] | [1, 2, 4] | example from the docstring |
digits = [1, 2, 9] | [1, 3, 0] | a single trailing 9 rolls over and carries once |
digits = [9, 9, 9] | [1, 0, 0, 0] | every digit is 9, the result grows a new leading digit |
digits = [9] | [1, 0] | smallest valid input, a single 9 that rolls over |
digits = [0] | [1] | smallest valid input, a single digit with no carry |
digits = [2, 9, 9] | [3, 0, 0] | carry propagates through two trailing 9s and stops |