This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging
Theory:
When we have two integers, a and b, we normally have the “+” operator to add them:
let sum = a + b;
Copy the code
However, JS has a safe range for storing integers, and any number beyond this range will lose accuracy.
We can’t run with the loss of accuracy, because the result of the operation will also be loss of accuracy.
So, we use strings to represent data! (Ensure accuracy is not lost)
The maximum safe range of integers in JS is: 9007199254740991
Let’s say we want to do 9007199254740991 + 1234567899999999999
The first number is just within safe range, the second number is well beyond safe range.
Let’s go to Google chrome and run the results of the two number addition operations: 1243575099254741000
And this is obviously not true, because we do a rough mental calculation of the mantissa and we know that it can’t end in 000.
So here’s a rudimentary scheme for representing large numbers as strings and adding them.
Body:
We need to prepare two string variables and a method:
let a = "9007199254740991";
let b = "1234567899999999999";
function add(a ,b){
/ /...
}
Copy the code
Then align the string length:
let a = "9007199254740991";
let b = "1234567899999999999";
function add(a ,b) {
// Take the maximum length of two digits
let maxLength = Math.max(a.length, b.length);
// Use 0 to complete the length
a = a.padStart(maxLength , 0); / / "0009007199254740991"
b = b.padStart(maxLength , 0); / / "1234567899999999999"
}
Copy the code
Then add from the ones place:
let a = "9007199254740991";
let b = "1234567899999999999";
function add(a ,b) {
// Take the maximum length of two digits
let maxLength = Math.max(a.length, b.length);
// Use 0 to complete the length
a = a.padStart(maxLength , 0); / / "0009007199254740991"
b = b.padStart(maxLength , 0); / / "1234567899999999999"
// Define the variables to be used during addition
let t = 0;
let f = 0; // "carry"
let sum = "";
for(let i = maxLength-1; i >= 0; i--){
t = parseInt(a[i]) + parseInt(b[i]) + f;
f = Math.floor(t / 10);
sum = t % 10 + sum;
}
if(f == 1){
sum = "1" + sum;
}
return sum;
}
Copy the code
Run:
add(a ,b);
Copy the code
The result is: 1243575099254740990
End