Home > database >  Can you tell me why my code for turning an array to a number, adding one, and returning an array onl
Can you tell me why my code for turning an array to a number, adding one, and returning an array onl

Time:06-07

I'm trying to solve the following Leetcode problem:

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

Example 1:

Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Incrementing by one gives 123 1 = 124. Thus, the result should be [1,2,4].

Here's my code :

var plusOne = function(digits) {
    
    let newDigit = digits.join('')
    if (newDigit.length > 15) {
        let digitLength = newDigit.length
        let secondHalf = newDigit.slice(digitLength - 15, digitLength)
        secondHalf = parseInt(secondHalf)   1
        secondHalf = Array.from(String(secondHalf), Number)
        digits.splice(digitLength - 15, 15)
        return digits.concat(secondHalf)
        
        
    
    }
    let Digit = parseInt(newDigit)   1
    const answer = Array.from(String(Digit), Number)
    return answer        
};

Works for many data sets. Get's the following error on the following set. Why :(

enter image description here

CodePudding user response:

When you do parseInt(secondHalf), you're effectively dropping any leading zeros in that string, and as a result those zeros don't get included in the final array. The input digits are guaranteed not to have any leading zeros, but that doesn't mean that there won't be any leading zeros if you slice the string in the middle.

Also, even fixing that, what about input arrays that are longer than 30 characters?

Consider using a BigInt instead, it'll be a lot easier.

const plusOne = function(digits) {
  const bigInt = BigInt(digits.join(''))   1n;
  return [...String(bigInt)].map(Number);
}

console.log(plusOne(
  '590840235570031372488506112'.split('').map(Number)
));

  • Related