23. Odometer Plus One
An old car has a mechanical odometer that shows one digit per wheel. The digits are stored in an array from the leftmost wheel to the rightmost, and together they spell a non-negative whole number with no unnecessary leading zeros. The car now drives one more kilometre, so the number goes up by exactly 1.
Write a method plusOne that takes the array digits and returns the array of digits showing the number after adding 1. A wheel that rolls over from 9 goes back to 0 and pushes 1 onto the wheel to its left; if the leftmost wheel rolls over, a new wheel showing 1 appears at the front.
Example 1
- Input:
- digits = [1,2,3]
- Output:
- [1,2,4]
- Explanation:
123 + 1 = 124, so only the last wheel changes.
Example 2
- Input:
- digits = [9,9]
- Output:
- [1,0,0]
- Explanation:
99 + 1 = 100: both wheels roll over to 0 and a new leading wheel shows 1.
Constraints
1 ≤ digits.length ≤ 100
0 ≤ digits[i] ≤ 9
digits has no leading zero, except for the number 0 itself
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)