JS implements the addition of two large numbers

When the value of two numbers exceeds the maximum value of the int type, the precision will be lost when added. However, if it is a string, the precision will not be lost, so you can start from the ones digit and add them bit by bit and finally spell them out.

function bigIntAdd(x, y) {
    const len = Math.max(x.length, y.length) // 取较长的数为要补0的长度
    // 将数的位数对齐
    x = x.padStart(len, '0')
    y = y.padStart(len, '0')
    let flag = '0' // 记录每个位相加时要进的位
    const queue = [] // 存储结果
    // 倒序从个位开始逐位相加
    for (let i = len - 1; i >= 0; i--) {
        const charX = x.charAt(i)
        const charY = y.charAt(i)
        // 求和时要加上上一次的进位
        const sum = Number(charX) + Number(charY) + Number(flag)
        // 十进制加法满十进一 判断是否要进1位 不进位则为0
        flag = sum >= 10 ? '1' : '0'
        // 取模得到当前位存入
        queue.unshift(sum % 10)
    }
    // 计算完毕后判断最高位是否产生了进位 如果产生了进位则补1
    if (flag === '1') {
        queue.unshift('1')
    }
    // 返回字符串表示形式
    return queue.join('')
}
console.log(bigIntAdd('1234567899999999999', '1')) // 1234567900000000000
console.log(bigIntAdd('9999999999999999999', '1111111111111111111')) // 11111111111111111110

Guess you like

Origin blog.csdn.net/Suk__/article/details/131748129