qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

第331题(2020-10-22):leetcode415:字符串相加(腾讯、字节) #334

Open qappleh opened 3 years ago

qappleh commented 3 years ago

给定两个字符串形式的非负整数 num1 和 num2 ,计算它们的和。

例如:

"111" + ”2222“ = ”2333“

注意:

附赠leetcode地址:leetcode

qappleh commented 3 years ago

解答:从低位开始相加

代码实现:

var addStrings = function(num1, num2) {
    let a = num1.length, b = num2.length, result = '', tmp = 0
    while(a || b) {
        a ? tmp += +num1[--a] : ''
        b ? tmp +=  +num2[--b] : ''

        result = tmp % 10 + result
        if(tmp > 9) tmp = 1
        else tmp = 0
    }
    if (tmp) result = 1 + result
    return result
};

复杂度分析: