Solving Leetcode: 66 Plus One in JavaScript

Tish Faroul
2 min readJul 14, 2022

The Problem:

From my understanding, we are given an array of numbers (called digits) where we have to increase the largest number by one.

Per example one, if we have the numbers: 1,2,3 we should make it so that 3 turns to 4. The final array would be [1,2,4].

But per example 3, if we have the number 9, the number 10 splits to [1, 0].

So, the first thing I need to do is loop through the given array backwards. If i greater than or equal to 0, we’ll move backwards.

function plusOne(digits){
for (let i = digits.length -1; i >= 0; i--){
}
}

Next, I’m going to check to see if the number at the back of the array is a 9. If it isn’t a 9, I’m going to increase the number by 1 and return the array.

function plusOne(digits){
for (let i = digits.length -1; i >= 0; i--){
if (digits[i] !== 9) {
digits[i]++;
return digits;
}
}
}

But if the number is a 9, we need to change that number to 0.

function plusOne(digits){
for (let i = digits.length -1; i >= 0; i--){
if (digits[i] !== 9) {
digits[i]++;
return digits
} else {
digits[i] = 0;
} }
}

But if all of the numbers in the array are 9, like this:

 [9,9,9]

We have to change all of the numbers to 0.

But remember, that per example 3, we have to now make the first number 1. To alter the first element in an array, we can use unshift.

function plusOne(digits){
for (let i = digits.length -1; i >= 0; i--){
if (digits[i] !== 9) {
digits[i]++;
return digits;
} else {
digits[i] = 0;
}
digits.unshift(1);
}
}

Finally, we return the array.

function plusOne(digits){
for (let i = digits.length -1; i >= 0; i--){
if (digits[i] !== 9){
digits[i]++;
return digits;
} else {
digits[i] = 0;
}
}
digits.unshift(1);
return digits;
}

✨✨✨And that’s it!

Tish⚡️🎧🌙

--

--