66/670

66. Plus One

Easy

You are handed digits, an array in which each element is one decimal digit of a large non-negative integer. Index 0 holds the most significant digit, and the array never starts with a 0 unless the number itself is zero (given as [0]).

Increment the number by one and return the digits of the result, in the same most-significant-first layout.

The number can be up to 100 digits long — far beyond any built-in integer type — so operate on the digit array itself.

Example 1:

Input: digits = [1, 2, 3]

Output: [1, 2, 4]

Explanation: The array encodes 123. Adding one gives 124, whose digits are [1, 2, 4].

Example 2:

Input: digits = [9, 9]

Output: [1, 0, 0]

Explanation: 99 + 1 = 100. The carry ripples through both nines and the answer grows one digit longer.

Constraints:

  • 1 ≤ digits.length ≤ 100
  • 0 ≤ digits[i] ≤ 9
  • The array has no leading zeros, except for the single-element array [0].

Hints:

Adding one only disturbs the rightmost digits: the carry travels left exactly as far as the trailing 9s reach.

Walk from the last index toward the front. A digit below 9 simply increments — you can stop right there. A 9 turns into 0 and pushes the carry left. If you run off the front of the array, every digit was a 9 and the result needs one extra leading 1.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: digits = [1, 2, 3]

Expected output: [1, 2, 4]