#66

Plus One

Easy Carry handling

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A large integer is stored as an array of digits, most significant first. Add one and return the new digit array.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: add 1 to a big number stored as a digit array.

Why this works: like adding on paper from the right. A 9 becomes 0 and carries; the first non-9 just goes up by one.

Example: [1, 2, 9, 9]

9 → 0 (carry), 9 → 0 (carry)2 → 3, stop[1, 3, 0, 0]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Converting the digits to an int or long — the array can be 100 digits long.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1), or O(n) in the all-9s case.