Kurapati Mahesh

Posted on

# plusOne Array of Integers in Javascript

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.

Alexander Staroselsky

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.

Frank Wisniewski

another classic way

``````  const plusOne = (a, i=a.length-1) => {
while (a[i]!=undefined){
if (a[i] != 9){
a[i]++;
return a
}
a[i]=0
i--
}
return [...[1],...a]
}
``````

Frank Wisniewski
``````  const plusOne = arr => (parseInt(arr.join(''))+1).toString().split('')

console.log(plusOne([1,2,3,9]))
console.log(plusOne([9]))
``````

Kurapati Mahesh

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].

Frank Wisniewski • Edited

you wrote integer...sorry

``````  const plusOne = arr => (BigInt(arr.join(''))+1n).toString().split('')

console.log(plusOne([1,2,3,9]))
console.log(plusOne([9]))
console.log(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]))
``````

Alex Lohr
``````const plusOne = (v) => [...(+v.join('') + 1).toString()]
``````

Kurapati Mahesh

Number conversion fails in case of large numbers. But, yeah that is worst case. Cool one Alex. Much more simplified.

Alex Lohr • Edited

Otherwise, we can use recursion:

``````const plusOne = (v, i) => i === undefined
? plusOne(v, v.length - 1)
: v[i] < 9
? (v[i]++, v)
: i === 0
? [1, 0, ...v.slice(1)]
: ((v[i] = 0), plusOne(v, i - 1))
``````

I love recursion for cases like this, because it makes the different branches really obvious.

Frank Wisniewski

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])
….

Frank Wisniewski

missing convert...

``````const plusOne = arr = (BigInt(arr.join(''))+1n).toString().split('').map(Number)
``````

Kurapati Mahesh

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.