CodingNodes / Math & Geometry / Plus One System design Space play · ←→ step · R restart

Problem

A non-negative whole number is stored in an array digits, one decimal digit per cell, with the most significant digit first. The number has no leading zeros, except that the number 0 itself is stored as one cell.

Add one to the number and return the digits of the result in the same format.

Constraints

  • 1 ≤ digits.length ≤ 100
  • 0 ≤ digits[i] ≤ 9
  • digits has no leading zero unless the number is 0

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: We walk left over the digits at most once, and stop early as soon as one digit is below 9.

Space: The digits are changed in place. Only when every digit is 9 do we build one new array of n + 1 cells.

Adding 1 only disturbs the trailing nines. Walk from the right: a 9 becomes 0 and the carry moves on; the first digit below 9 just goes up by one and we are done. If we run out of digits, the answer is 1 followed by zeros.