~/problems / Math & matrices

Plus One

easy ~10 min

An odometer stores a non-negative whole number as a list of its decimal digits, most significant digit first. The number has no leading zeros, except that zero itself is [0].

Write add_one(digits) -> list that returns the digits of the number plus one, in the same format.

add_one([1, 2, 3])   # [1, 2, 4]
add_one([4, 9, 9])   # [5, 0, 0]
add_one([9, 9])      # [1, 0, 0]
add_one([0])         # [1]
  • 1 <= len(digits) <= 10^5, each digit is in 0..9.
  • The number can be far too long for a machine integer, so work with the digits directly instead of converting the whole list to a number.
  • Aim for O(n) time.
Show hint

think about how you add one by hand: which digits can actually change, and when do you get to stop?

Topic: Math and matrices. Digit-by-digit arithmetic, matrix rotation and in-place tricks.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc