KatInterview

Bump a Digit-Array Number Up by One

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashingarrayscarrysimulation

Last updated

Increment a large non-negative number stored as a digit list by one, handling carry propagation and length growth without converting to an integer.

Increment a Number Stored as Digits

A non-negative integer is stored in a list of decimal digits, with the most significant digit first (at index 0). For example, the number 407 is stored as [4, 0, 7].

Write a function that adds exactly one to this number and returns the digits of the result in the same format.

Rules

  • Do the arithmetic digit by digit, carrying as needed. Do not convert the whole list into a single integer and do not build the result with a growing, dynamically resized collection. The result should be sized correctly up front.
  • If the addition makes the number longer (for example [9, 9] becomes [1, 0, 0]), return a list that is one element longer than the input.
  • Otherwise the returned list has the same length as the input.
  • The returned list must not have leading zeros, except when the value itself is zero. Given the constraints, the only zero input is [0], and its answer is [1].
  • The input list should be left unchanged; return a new list.

Constraints

  • 1 <= len(digits) <= 1000
  • 0 <= digits[i] <= 9
  • The input has no leading zeros unless it is exactly [0].

Examples

Example 1

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

Output: [1, 2, 4]

Example 2

Input: increment_digits([9, 9])

Output: [1, 0, 0]

Example 3

Input: increment_digits([8, 9, 9])

Output: [9, 0, 0]

Hints

Hint 1

Adding one only affects the trailing run of 9s and the digit immediately before that run. Everything further left stays the same.

Hint 2

Walk from the last index toward the front. If a digit is below 9, increment it and you can return immediately. If it is 9, set it to 0 and keep moving left.

Hint 3

If the loop finishes without returning, every digit was 9 and is now 0. The answer is a 1 followed by all those zeros, so the length grows by one.