Increment the large integer by one and return the resulting array of digits.
Example:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
Here is the my implementation:
function plusOne(digits: number[]): number[] {
let n = digits.length;
for(let i=n-1; i>=0; i--) {
if(digits[i] < 9) {
digits[i]++; return digits;
}
digits[i] = 0;
}
let newArr = Array.from({length: n+1}, () => 0);
newArr[0] = 1;
return newArr;
};
Please provide if you have more simplified and better solution.
Thanks.
Top comments (11)
It’s important to remember that this is an interview question and they will press you on different ways to achieve this. Even if you use a BigInt and solve the question, depending on the level they will ask you to solve it without BigInt as well as explain the time and space complexity of your answer. So knowing how to do it with a loop and without string manipulation will likely be very important.
another classic way
Cool one. Thanks. But this fails in case of large arrays like..
[3,4,5,6,7,8,,1,2,3,1,2,3,4,5,6,7,8,8,4,3,2,5,6,7].
you wrote integer...sorry
Number conversion fails in case of large numbers. But, yeah that is worst case. Cool one Alex. Much more simplified.
Otherwise, we can use recursion:
I love recursion for cases like this, because it makes the different branches really obvious.
plusOne([3,4,5,6,7,8,1,2,3,1,2,3,4,5,6,7,8,8,4,3,2,5,6,9,3,3,3,3,9])
….
missing convert...
Good. One. I think each time array needs to be converted completely even though the last digit is 9 or not.
any how, its simplified thanks.