美文网首页
415. Add Strings

415. Add Strings

作者: jluemmmm | 来源:发表于2020-09-05 14:36 被阅读0次

    大数相加

    逐个相加Math.max(m, n)次

    • Runtime: 88 ms, faster than 77.02%
    • Memory Usage: 39.5 MB, less than 29.59%
    • 时间复杂度 O(Math.max(m,n))
    • 空间复杂度 O(1)
    /**
     * @param {string} num1
     * @param {string} num2
     * @return {string}
     */
    var addStrings = function(num1, num2) {
        let m = num1.length - 1
        let n = num2.length - 1
        let carry = 0
        let res = ''
        while(m >= 0 || n >= 0 || carry !== 0) {
            let x = m < 0 ? 0 : (num1[m--] - '0')
            let y = n < 0 ? 0 : (num2[n--] - '0')
            let sum = x + y + carry
            carry = parseInt(sum / 10)
            res = (sum % 10) + res
        }
        return res
    };
    

    逐个相加Math.min(m, n) + 1次

    • Runtime: 84 ms, faster than 89.03%
    • Memory Usage: 39.5 MB, less than 27.42%
    • 时间复杂度 O(Math.min(m,n))
    • 空间复杂度 O(1)
    /**
     * @param {string} num1
     * @param {string} num2
     * @return {string}
     */
    var addStrings = function(num1, num2) {
        let m = num1.length - 1
        let n = num2.length - 1
        let res = ''
        let carry = 0
        while((m >= 0 && n >= 0) || carry !== 0) {
            let x = m < 0 ? 0 : (num1[m--] - '0')
            let y = n < 0 ? 0 : (num2[n--] - '0')
            let temp = x + y + carry
            carry = parseInt(temp / 10)
            res = temp % 10 + res
        }
        if(m >= 0) res = num1.substr(0, m + 1) + res
        if(n >= 0) res = num2.substr(0, n + 1) + res
        return res
    };
    

    相关文章

      网友评论

          本文标题:415. Add Strings

          本文链接:https://www.haomeiwen.com/subject/edrzsktx.html