Javascript coding exercise

Javascript coding exercise
0

#1

I am doing this coding exercise on leetcode.com and am getting unexpected output
https://leetcode.com/problems/plus-one/description/

The function is supposed to receive an array of single numbers, but you treat the array as a full number and add 1.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

My code

var plusOne = function(digits) {
    let str = ''
    for(let num of digits) {
        str += num
    }
    let num = parseInt(str);
    num++;
    let strArr = [...num.toString()]
    let finArr = []
    let temp = 0;
    for(let item of strArr) {
        temp = parseInt(item)
        finArr.push(temp)
    }
    
    return finArr
};
Input: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]

In this test case the final 3 indexes are getting pushed as 0's and I cannot figure out why.
Any ideas?


#2

In JavaScript, the highest number which you can reliably perform math operations on is 9,007,199,254,740,991

Any number higher than that like your 6,145,390,195,186,705,543 will not produce numbers you expect. You would need to use an extra library specifically designed to handle JavaScript’s limitations or create your own. See this link for more information.

Do you have to do this in JavaScript? If not, then I highly recommend Python which is better suited for integer numbers this large.


#3

I think you should do a different implementation. Add 1 to the digit in the highest index position if the number is less than 8. If 9 then change 9 to 0 and add one to the previous index number (if it is less than 8) etc. So basically treat it like someone doing a vertical addition calculation in math class.


#4

I think that @hbar1st has pointed you to the intention of the challenge.


#5

Yeah I was thinking of a solution like this but I suck at recursion and am not too keen to implement a bunch of for’s and if’s.
I’ll see how it goes thanks


#6

Thanks for the info.

Dont have to use JS but I am primarily practicing the JS for job interviews.


#7

The trick to recursion is to know when to stop. So always code the stop condition first. That is, if you are given an array with a single number, how would you add one to it? If you can write this code to work for 0 to 9 then you can solve the whole thing.

However i imagine just looping backwards through the array will solve this, so no recursion needed.


#8

There is another way to solve this problem if you only look at the last digit. If you add 1 to the last digit and the sum is less than 10 then you can just switch out the last digit with the sum. Otherwise, you need to traverse the array in reverse repeating the sum on each digit until the sum is less than 10 and updating the previous digits accordingly.


#9

Not sure if you came up with a solution, but here is one possible imperative solution which mutates digits. If you do not want to mutate digits, then you would need to make a copy first and then substitute the copied array where ever you see digits referenced inside the function.

const plusOne = digits => {
  let i = digits.length - 1;
  while (i >= 0) { 
    const addOne = digits[i] + 1;
    if (addOne < 10) {
      digits[i] = addOne;
      return digits;
    }
    digits[i--] = 0;
  }
  return digits[0] === 0 ? [1, ...digits] : digits;
};

I am working on a refactor which could simplify the code a bit more, but having some trouble getting it to work. Also, I believe this could be converted to a recursive function without too much trouble. If someone does not post a recursive solution, then I may attempt one.


#10

This problem isn’t a bad candidate for recursion, but if I were to solve it recursively it would look very much like the imperative solution discussed here.


#11

Thanks for everyones input, the info from @RandellDawson about math operations on large Javascript numbers is really good to know.

I ended up with this solution built from the advice of @hbar1st

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

Ends up being a lot easier than I thought with a while loop, and much better than my first implementation.


#12

Yes, your solution is similar to the one I posted earlier.


#13

Yeah cheers rando, I need to get better at reading/writing shorthand and ES6 JS syntax.

I had to read the ternary statement in your return like 10 times before I understood it.


#14

I could have written the last line as without using any ES6 syntax.

return digits[0] === 0 ? [1].concat(digits) : digits;