大数相加

168 阅读1分钟
const sumBigNumber = (str1, str2) => {
    // 参数也应该传字符串,不然精度可能就已经丢失了;
    let len1 = str1.length - 1
    let len2 = str2.length - 1
    let carry = 0 // 进位
    const res = []

    while(len1 >= 0 || len2 >= 0 || carry > 0/* 有可能还有进位,所以继续加 */) {
            
            const number1 = len1 >= 0 ? str1[len1--] - '0' : 0
            const number2 = len2 >= 0 ? str2[len2--] - '0' : 0
    
            const sum = number1 + number2 + carry

            carry = sum >= 10 ? 1 : 0
            res.unshift(sum % 10)

    }
    return res.join('')
}