Solving in JS. Add One

Dong Xia
3 min readJan 4, 2021

--

Level — Easy

We are given this question.

You are given a list of integers nums, representing a decimal number and nums[i] is between [0, 9].For example, [1, 3, 9] represents the number 139.Return the same list in the same representation except modified so that 1 is added to the number.Constraints
n ≤ 100,000 where n is the length of nums.

We are given nums = [1,3,9] and we want the answer to be [1,4,0].

This question seems straight forward. My initial approach is convert it into a string “139” then convert it into a number 139 and add 1. Resulting 140. Now I just need to convert it back into an array [“1”, “4”, “0”]. Now I need to iterate each index to convert it back to a number. Resulting a final answer of [1,4,0].

However, there is a flaw in this approach. This works only for the safe integers. As we approach super large value, converting a string into a number. The result will differ from what we expected. According to MDN documentations.

The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent integers between -(2^53 - 1) and 2^53 - 1

We now need to use a different approach.

When we do arithmetic we start from the right and move towards the left. When are at 9, it becomes 0. Then we carry the 1 over to the left. The same idea can be applied to this array.

Back to our example of nums = [1,3,9].

We can use a for loop going from the last index to the first index.

for(let i = nums.length; i >= 0; i --{}

We need to check if the nums[i] < 9, if so we can just add 1 and return the result. Otherwise if nums[i] === 9, we need to make nums[i] = 0 and move to the left or previous index position.

for(let i = nums.length; i >= 0; i --{
if(nums[i] < 9){
nums[i] += 1
return nums
}else{
nums[i] = 0
}
}

index [0,1,2]

nums[1,3,9]

The first iteration nums[2] === 9. The if statement is false. Since 9 is not less than 9, we move into the else statement, we reassign nums[2] = 0. Our current array is now [1,3,0].

Now we our in the second iteration nums[1] === 3. The if statement is true. Since 4 is less than 9, we reassign and add 1. nums[1] = nums[1] + 1 same as nums[i] += 1 . Our current array is now [1,4,0]. We return that array and exit the loop.

If we have [9,9], our result will return [0,0]. To solve this issue, we need to add 1 to the beginning of this new array.

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

--

--

Dong Xia
Dong Xia

Written by Dong Xia

Copy and Paste what’s on my mind. Perfect.

No responses yet