progress

~/problems / Math & matrices

Plus One

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

An odometer stores a non-negative whole number as a list of its decimal digits, most significant first, with no leading zeros (zero 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.
  • ⭐ Bonus: a speed test with 100,000 digits earns a star in O(n).
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