KatInterview

Add One to Array-Represented Number

Arrays & HashingAuto-graded · 19 test cases
MediumAuto-gradedArrays & Hashingarrayssimulationmath

Last updated

Tests array manipulation and carry logic when adding one to a number stored as an array of digits.

You receive an array of digits where each element holds a single digit (0-9), and the array represents a non-negative integer with the most significant digit at index 0. The number has no leading zeros unless the number itself is zero.

Write a function that adds one to this number and returns the resulting digit array.

Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9
  • The input represents a valid non-negative integer (no leading zeros except for zero itself)

Examples

Example 1

Input: add_one_to_digits([1, 2, 3])

Output: [1, 2, 4]

Example 2

Input: add_one_to_digits([9, 9])

Output: [1, 0, 0]

Example 3

Input: add_one_to_digits([0])

Output: [1]

Hints

Hint 1

Start from the rightmost digit and work backward, just like adding by hand on paper.

Hint 2

When a digit is less than 9, you can add one and stop immediately—no carry needed.

Hint 3

If all digits are 9, the result will need one more digit at the front.