Plus One

25 min · plusOne()

A calculator has the whole number. You have one decimal digit per array slot — and the number may be a hundred digits long.

Given an array digits representing a non-negative integer, add one and return the resulting digit array. The most-significant digit—the digit with the greatest place value—comes first.

A few ground rules:

  • Every array entry is one decimal digit from 0 through 9.
  • The number has no leading zero unless the entire number is [0].
  • The answer may need one extra slot. A carry is the extra value passed into the next place when a digit reaches ten.

Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9
  • digits[0] != 0 unless digits is [0].

Hints

Where does addition begin?

Adding one changes the last digit first. Start at the right edge, just as you would when adding numbers on paper.

A nine passes the work left

If the current digit is below 9, increment it and stop. If it's 9, write 0 there and keep carrying one toward the front.

What if every digit was nine?

After the carry crosses the whole array, every old digit is 0. Put a new 1 at the front.

Follow-up

Can you finish with constant extra space, ignoring the array you return?

Visible cases

Examples

Example 1

ready
Input
digits = [
  1,
  2,
  3
]
Expected
[
  1,
  2,
  4
]
Why
the final digit absorbs the extra one

Example 2

ready
Input
digits = [
  9
]
Expected
[
  1,
  0
]
Why
a one-digit carry grows the array

Example 3

ready
Input
digits = [
  4,
  3,
  2,
  1
]
Expected
[
  4,
  3,
  2,
  2
]
Why
only the least-significant digit changes

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite