LeetCode 415. 字符串相加 (Add Strings)[简单]

lework · 2020年06月12日 · 最后由 lework 回复于 2020年06月12日 · 141 次阅读

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

注意:

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-strings 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        res = ""
        i, j, carry = len(num1) - 1, len(num2) - 1, 0
        while i >= 0 or j >= 0:
            n1 = int(num1[i]) if i >= 0 else 0
            n2 = int(num2[j]) if j >= 0 else 0
            tmp = n1 + n2 + carry
            carry = tmp // 10
            res = str(tmp % 10) + res
            i, j = i - 1, j - 1
        return "1" + res if carry else res
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册