Example 1
- Input
- digits = [1, 2, 3]
- Output
- [1, 2, 4]
The array represents 123. Adding one gives 124, so only the final digit changes and the result is [1, 2, 4].
Add one to a non-negative integer stored as an array of its decimal digits, most significant first, and return the resulting digit array.
You are given a large non-negative integer as an array digits, where each entry holds one decimal digit ordered from most significant to least significant. Add one to the integer and return the resulting array of digits.
The integer can be too long for any native number type, so the addition must happen digit by digit. A trailing run of 9 digits rolls over to 0 and carries left, and an input of all 9 digits grows the array by one ([9] becomes [1, 0]).
[0].The array represents 123. Adding one gives 124, so only the final digit changes and the result is [1, 2, 4].
The array represents 4321. Adding one gives 4322; the final 1 absorbs the increment without carrying left.
Adding one to 9 produces 10. The original digit rolls over to 0, and the carry becomes a new leading 1.
The units and tens digits each roll from 9 to 0. Their carry reaches the hundreds digit, increasing 2 to 3; the leading 1 stays unchanged.
Start at the units digit, where adding one first acts. A digit below 9 absorbs the increment and leaves everything to its left unchanged. A 9 becomes 0 and sends one carry left; for [1, 2, 9, 9] that changes the last two digits to zeros and the 2 to 3. Example 1 has no trailing 9, so only its 3 changes to 4. If every digit rolls over, a new leading 1 is required.
Reveal Convert and Add: intuition, complexity, and code
129: only the trailing 9 flips, then the 2 absorbs the carry.9 into 0 and stop at the first digit below 9 by adding one to it.9, nothing absorbed the carry, so the answer is 1 followed by all 0 digits in a new array.[0] increments to [1] and retains the original object in the carry approach.9 becomes [1, 0]; an all-9 array of length 100 becomes a leading 1 followed by 100 zeros.[1, 2, 9, 9], rolls over only until the first earlier non-9 digit absorbs the carry.int or 64-bit long and adding one, which overflows once the input passes 10 or 19 digits.9 input instead of allocating the longer [1, 0, ..., 0] result.9 absorbs the increment, flipping earlier digits that should stay fixed.Digit-array arithmetic runs right to left so carries flow naturally, and the all-max-digit input always needs its own branch.