Was working on a leetcode problem that want me to add a value to an array form. LINK TO PROBLEM
It works for all of the examples expect the one in the console log below. For some reason parseInt drops the last two digits (6,3) and replaces them with zeros.
Why is this?
var addToArrayForm = function(A, K) {
let number = A.join('');
number = parseInt(number, 10);
number += K;
return number.toString().split('');
};
console.log(
addToArrayForm(
[1, 2, 6, 3, 0, 7, 1, 7, 1, 9, 7, 5, 6, 6, 4, 4, 6, 6, 6, 3],
516
)
);
This isn't parseInt, but the way JavaScript stores numbers, which is 64 bit floating point. You just don't have enough precision to store those last digits in such a format. It can actually be demonstrated on the very number you've tested it on just tracing it out to console (snippet below).
Workaround do exists, for example, you can use BigInt, but i really don't think your exercise wants you to dive into this.
console.log("12630717197566446663");
console.log(12630717197566446663);