A large integer is given as an array of its digits, most significant first, with no leading zeros. Return the digits of the integer plus one.
Scan from the right. A 9 becomes 0 and the carry moves on; the first digit below 9 just goes up by one and we are done. If every digit was 9, the answer is 1 followed by zeros.
1function plusOne(digits: number[]): number[] {2for (let i = digits.length - 1; i >= 0; i--) {3if (digits[i] < 9) { digits[i]++; return digits; }4digits[i] = 0;5}6return [1, ...digits];7}
9 rolls over to 0; carry continues left.
Space: play/pause · ←/→: step