Mohamed Ibrahim
Mohamed Ibrahim

Reputation: 57

How to convert a long string (more than 16 digits) into numbers

this is a function just increment one number into array but the problem i interface when i put alot of numbers into array (more than 16 digits) when i use parseInt() just returned 16 correct numbers and more than that be zero

6145390195186705000

and expected

6145390195186705543

the function

var plusOne = function(digits) {
    var numbersInString = digits.join('');
    var theNumbers = parseInt(numbersInString);
    var theNumbersPlusOne = theNumbers + 1;
    var result = String(theNumbersPlusOne).split("").map((theNumbersPlusOne) => {
        return Number(theNumbersPlusOne);
    });
    return result;
};

console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));

Upvotes: 0

Views: 2742

Answers (2)

Liftoff
Liftoff

Reputation: 25392

Just expanding on my above comment with another solution...

You've exceeded the maximum safe integer value. (Number.MAX_SAFE_INTEGER, which equals 9007199254740991). Numbers larger than this are not supported with standard integer types in javascript, or rather there's not enough precision to represent them. Anything larger than this is represented in scientific notation and the extra digits are truncated and represented only as zeroes.

With that said, you don't even need to convert the array to a string to an integer just to increment it. You can just increment the individual digits in the array, starting at the end and working your way forwards to "carry the 1" so to speak.

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

console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));

Upvotes: 3

zahl
zahl

Reputation: 300

You can use BigInt to handle this problem.

var plusOne = function(digits) {
    var numbersInString = digits.join('');
    var theNumbers = BigInt(numbersInString);
    var theNumbersPlusOne = theNumbers + BigInt(1);
    var result = theNumbersPlusOne.toString().split("").map((theNumbersPlusOne) => {
        return Number(theNumbersPlusOne);
    });
    return result;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));

Upvotes: 3

Related Questions