A non-negative whole number is stored as a list digits, one digit per entry, with the most significant digit first. The number has no leading zeros, except for the number 0 itself.
Add 1 to the number and return the result in the same digit-list form.
Example 1
Input: digits = [3, 7, 9, 9] Output: [3, 8, 0, 0] Why: 3799 + 1 = 3800
2 more examples and the constraints
Example 2
Input: digits = [5, 0, 2] Output: [5, 0, 3] Why: the last digit is not 9, so nothing carries
Example 3
Input: digits = [9, 9] Output: [1, 0, 0] Why: 99 + 1 = 100, one digit longer
Constraints
- 1 ≤ length of digits ≤ 100
- 0 ≤ digits[i] ≤ 9
- No leading zeros, unless the number is 0
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Full carry passO(n)
- Stop at the first non-9O(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 digits | Verdict |
|---|---|---|---|
| Full carry pass | O(n) | Passes; always reads every digit | |
| Stop at the first non-9 | O(n) | Best; stops early, in place |
n = number of digits. Work is for a typical input whose carry stops early.
Edge cases to test
- All nines. [9, 9] becomes [1, 0, 0]; the list gets longer.
- The number 0. [0] becomes [1].
- Carry stops in the middle. [1, 0, 9] becomes [1, 1, 0]; the front digit is untouched.
- No carry at all. [5, 0, 2] only changes the last digit.
Common mistakes
- Turning the digits into an int or long, which overflows long before 100 digits.
- Forgetting the all-9s case and returning [0, 0] for [9, 9].
- Adding 1 to every digit, or walking from the front instead of the back.
How to talk through it
- 1Clarify. Most significant digit first? Can I change the input list? Is [0] a valid input?
- 2Rule out the shortcut. Converting to a number overflows at 100 digits, so do the addition by hand.
- 3Name the two cases. A 9 becomes 0 and carries; any other digit takes the 1 and stops the carry.
- 4Code it. Loop from the right, return early, and handle the all-9s case after the loop.
- 5Test out loud. Run [9, 9], [0] and [1, 0, 9] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?