1. Why solve the problem of adding large numbers

JS has a safe range for storing integers. If the number exceeds this range, it will lose accuracy. We can't run with a loss of precision, because the result is also a loss of precision. So, we need to solve the accuracy loss problem. The maximum security range of the integer in JS is 9007199254740991Copy the code

2. Use the complement method to solve the problem of adding JS large numbers

let a = '1234567891011' let b = '123456789' //1. If (a.length>b.length){let arr = Array(a.length-b.length).fill(0); The // join() method is used to put all the elements of an array into a string. Elements are separated by the specified delimiter. b = arr.join('')+b }else if(a.length<b.length){ let arr = Array(b.length-a.length).fill(0); a = arr.join('')+a } let c = Number(a)+parseInt(b); console.log(c);Copy the code

3. Reverse two numbers (this is because people tend to add from left to right, and numbers add from right to left, so it is easier to understand the reverse)

            The reverse() method is used to reverse the order of elements in an array.
            a = a.split(' ').reverse();
            b = b.split(' ').reverse();
Copy the code

4. Loop through two arrays and add if sum is greater than 10 then sign = 1 and the current position is (and %10)

             let sign = 0;// flag whether to carry
            let newVal = [];// Used to store the final result
            for(let j = 0; j<a.length; j++){let val = a[j]/1+b[j]/1+sign;// If you divide by 1, you can use Number()
                if(val>=10){
                    sign = 1;
                    newVal.unshift(val%10)// Use unshift instead of push because you can avoid using reverse
                }else{
                    sign = 0;
                    newVal.unshift(val)
                }
            }
            
            let result = newVal.join(' ');
            console.log(result)
Copy the code

5. God lite

        function addBig(a, b) {
            let temp = 0,
                res
            a = a.split('');
            b = b.split('');
            while (a.lenght || b.length || temp) {
                temp += wwa.pop() + nurb.pop();
                res
                    (temp % 10) + res;
                temp = temp > 9;
            }
            return res.replace(/^0+/g, ' ');
        }
Copy the code