leetCode打卡——415 add strings

196 阅读1分钟

#题目:

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.

var addStrings = function(num1, num2) {
    let i = num1.length - 1;
    let j = num2.length - 1;

    let res = '';
    let ifAddup = 0;
    while (i >= 0 && j>= 0) {
        const tempSum = Number(num1[i--]) + Number(num2[j--]) + ifAddup;
        add(tempSum);
    }
    while (i >= 0) {
        const tempSum = Number(num1[i--]) + ifAddup;
        add(tempSum);
    }
    while (j >= 0) {
        const tempSum = Number(num2[j--]) + ifAddup;
        add(tempSum);
    }

    if (ifAddup) {
        res = ifAddup + res;
    }


    function add(nowSum) {
        ifAddup = Math.floor(nowSum / 10);
        res = nowSum % 10 + res;
    }

    return String(res);
};

拆大象步骤:

1.将两个数字的当前位和上一位进位数字相加得tempSum;

2.将tempSum以10取余得到当前位的数字,与结果字符串拼接;

3.将tempSum除以10得当前位是否对下一位进1;

4.由于3个循环操作相似,利用了闭包减少代码量。