Search code examples
javascriptarraysdata-structuresdata-conversion

parseInt("number length greater than 15")


I was solving a problem in leet code, Solution I came up with made all test cases passed except for one. Input of that test case is an array = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]. so I have convert the array into a number add 1 to entire number and then convert it back to array format with result, in my solution one step before final statement, I have used parseInt("6145390195186705543")+1 then I convert to string and split and then convert to number. but during parseInt(), this in-built method is not able to convert after 15th digits, im getting output as [6145390195186705000], sending 0's after 15 digits, so does anyone has any idea on how to convert a string of number length more than 16 to Number P.S: I have tried bigInt() method, techincally it would work but for the problem bigInt() is not working and output isnt working

var plusOne = function(digits) {
  let y = digits.map(String);
  let z = ''
  for (let i = 0; i < y.length; i++) {
    z += y[i];
  }
  let a = (parseInt(z) + 1).toString().split('')
  return a.map(Number)
};

Solution

  • Loop backwards over the digits, and

    • if the digit is less than 9, add 1 and stop
    • otherwise the digit is 9, so set it to 0 and if the 9 was the first digit in the array, insert a 1 at the beginning of the array

    function addOne(digitArray) {
      for (let i = digitArray.length - 1; i >= 0; i--) {
        if (digitArray[i] < 9) {
          digitArray[i] += 1
          break
        } else {
          digitArray[i] = 0
          if (i === 0) {
            digitArray.unshift(1)
          }
        }
      }
      return digitArray
    }
    
    console.log(addOne([]))         // []
    console.log(addOne([ 0 ]))      // [ 1 ]
    console.log(addOne([ 9 ]))      // [ 1, 0 ]
    console.log(addOne([ 1, 0 ]))   // [ 1, 1 ]
    console.log(addOne([ 1, 9 ]))   // [ 2, 0 ]
    console.log(addOne([ 9, 9 ]))   // [ 1, 0, 0 ]
    
    console.log(addOne([ 6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3 ]))
    // [ 6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3 ]