KatInterview

Increment Large Integer Represented as Digits

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingarraysmath-bitseasy

Last updated

Process an array of decimal digits representing a non-negative integer by adding one, correctly handling carry propagation and list expansion.

You are given an array of integers representing the digits of a non-negative whole number. The array stores digits such that the most significant digit is at index 0 and the least significant digit is at the end of the array.

Write a function to add 1 to the integer represented by the digits and return the updated sequence of digits as a list.

Assume the integer contains no leading zeros, except when representing the value 0 itself.

Constraints

  • 1 <= len(digits) <= 100
  • 0 <= digits[i] <= 9

Examples

Example 1

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

Output: [1, 2, 4]

Example 2

Input: plus_one([9, 9])

Output: [1, 0, 0]

Hints

Hint 1

Start adding from the least significant digit (the end of the list) and work backward.

Hint 2

If a digit is less than 9, incrementing it will not generate a carry, so you can stop early.

Hint 3

If all digits are 9, every digit turns to 0 and you will need to insert a leading 1 at the front.