Plus One
Difficulty: Easy
You're given a very large non-negative number as a list of its digits (so [1, 2, 3] is 123). There are no leading zeros, except for the number 0 itself.
Add one and return the new digits as a list, in the same order.
Examples
Input: digits = [1, 2, 3]
Output: [1, 2, 4]
123 + 1 = 124.
Input: digits = [9, 9, 9]
Output: [1, 0, 0, 0]
999 + 1 = 1000 - the extra digit means the result has one more digit than the input.
Input: digits = [0]
Output: [1]
Constraints
1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading zeros, except for the number 0 itself.
Approach
A tempting shortcut treats the digits as one big number: join them, add one, and split the result. This only works because of a big-number type. An ordinary floating-point number loses precision once the list is long enough.
The robust way mirrors adding by hand. Start from the last digit. If it isn't 9, add one and you're done. If it is 9, it wraps to 0 and you carry the 1 to the digit on its left, repeating the check there. The only special case is when every digit is 9 (like 999): the carry runs off the front, so add a new leading 1.
Solutions
Convert to a Number
Join the digits into a string, convert it to a big-number type so no precision is lost, add one, and split the result back into digits.
function plusOne(digits) {
const num = BigInt(digits.join(""));
const incremented = (num + 1n).toString();
return incremented.split("").map(Number);
}Time: O(n) · Space: O(n)
Optimal - Digit by Digit With Carry
Walk the digits right to left. When a digit is less than 9, add one and return. Otherwise it wraps to 0 and the carry moves left. If the carry passes the front, every digit was 9, so prepend a 1.
function plusOne(digits) {
for (let i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
// Every digit was a 9 (e.g. 999 -> 1000): prepend a new leading 1
return [1, ...digits];
}Time: O(n) · Space: O(1) extra space, aside from the rare case that adds a new leading digit