Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]));

>Solution :

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]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading