Skip to content
This repository has been archived by the owner on Feb 14, 2023. It is now read-only.

415. 字符串相加 #33

Open
AmelloAster opened this issue Aug 3, 2020 · 0 comments
Open

415. 字符串相加 #33

AmelloAster opened this issue Aug 3, 2020 · 0 comments
Labels
Easy 史莱姆 Finished 经验+1 Leetcode daily topic 每日药丸 金金 Code is life

Comments

@AmelloAster
Copy link
Collaborator

415. 字符串相加

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

注意:

num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

解题代码

var addStrings = function (num1, num2) {
    let i = num1.length - 1;
    let j = num2.length - 1;
    let add = 0;
    let ans = '';
    while ( i >= 0 || j >= 0 || add !== 0 ) {
        let x = i >= 0 ? num1[i] - '0' : 0;
        let y = j >= 0 ? num2[j] - '0' : 0;
        let sum = x + y + add;
        ans += (sum % 10);
        add = Math.floor( sum / 10 );
        i -= 1;
        j -= 1;
        // console.log( i, j, sum, sum % 10 )
    }
    // console.log( ans )
    return ans.split('').reverse().join('')
};

解题思路

记录 nums1[i] + nums2[j] 的和的除数 用于下次相加的进位数
最后翻转结果

解题效率

执行用时:
96 ms, 在所有 JavaScript 提交中击败了33.72%的用户
内存消耗:
40.3 MB, 在所有 JavaScript 提交中击败了23.53%的用户
@AmelloAster AmelloAster added 金金 Code is life Leetcode daily topic 每日药丸 Easy 史莱姆 Finished 经验+1 labels Aug 3, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Easy 史莱姆 Finished 经验+1 Leetcode daily topic 每日药丸 金金 Code is life
Projects
None yet
Development

No branches or pull requests

1 participant