Approach – BigInt
This one was pretty straight forward though it had an interesting test case post submit. I joined the array into a string, then converted that to a Number()
to add 1 then result number to convert to an array of the digits. My initial solution passed all the local test cases, though I failed on the submission test cases. While console logging I noticed the end of the array was full of zeros and realized an Integer
wasn’t going to cut it. I knew I needed to switch to a BigInt
though I did learn that I needed to add the n
to the digit being added to a BigInt
. This was a fun one. Time Complexity O(N).
Here is my solution, it could be optimized though this was my accepted solution with good enough performance:
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
// Join the numbers into a single integer and add 1.
// Using a BigInt to cover larger numbers in test cases
// The `n` in the +1 is required to add to a BigInt to atch the type
const incremented = BigInt(digits.join(''))+1n;
// Use a map to convert the split strings back to integer
return([...incremented + ''].map(n => + n));
};