CodeArchon

easyMath & GeometryGoogle

Odometer Rollover

An odometer adds 1 to a large non-negative integer stored as a digit array, propagating carries.

Given a non-empty array of decimal digits representing a non-negative integer, increment the integer by one and return the resulting digits.

Choose approach

1
0
2
1
4
2
i
Mapdigits
0→1
1→2
2→4
1/1
Narrationstep 1 of 1

d[2] < 9, increment → 4. Done.

1def plusOne(digits):
2 for i in range(len(digits) - 1, -1, -1):
3 if digits[i] < 9:
4 digits[i] += 1
5 return digits
6 digits[i] = 0
7 return [1] + digits
Variables
i=2
result=124

How to think about it

  1. All-9s case produces a new leading 1.
  2. No digit < 9 early-exits in O(n).

Edge cases to catch in interview

  • [0] -> [1].
  • [9,9,9] -> [1,0,0,0].

Examples

Example 1[1,0,0]
{"digits":[9,9],"values":[9,9]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed