Add one from the right
Walk from the last digit. A 9 becomes 0 and the carry keeps going; anything else increments and we stop. A leftover carry prepends 1.
Same addition-on-paper as Add Two Numbers, but the addend is always 1.
Algorithm
- From the right, if the digit is 9 set it to 0 and continue.
- Otherwise increment and return.
- If every digit was 9, prepend 1.
- Time
- O(n)
- Space
- O(1)
class Solution: def plusOne(self, digits: list[int]) -> list[int]: out = digits[:] for i in range(len(out) - 1, -1, -1): if out[i] < 9: out[i] += 1 return out out[i] = 0 return [1] + out