leetcode: Plus One : JavaScript submission beats 99.90% in memory usage

Posted on Updated on

What the problem is asking for is to take the array and treat the whole thing as an integer. So [1,2,3] is the number 123, and if you add 1 that is 124. Then you would return [1,2,4].

You cannot just add 1 to the end, because for [5,6,9] you would need to return [5,7,0]. 569 + 1 = 570

Another thing to consider is that if the input is [9,9,9] then the returned array is larger having values [1,0,0,0]. 999 + 1 = 1000

The code I used is below. You can’t use the join, convert to number trick since some of the inputs are too large and then are rounded up loosing the trailing digits.

var plusOne = function(digits) {
    // return (parseInt(digits.join(""))+1).toString().split("")
    //the above looses precision when the number is too large
 
    for(let i=digits.length-1;i>=0; i--){
        if(digits[i]<9){digits[i]=digits[i]+1; return digits}
        digits[i]=0
    }
    //if we are here the first value in array was a 9
    digits.unshift(1)
    return digits
};

My runtime only beat 10.41% of the solutions. Great on memory, poor on performance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s