415. 字符串相加
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
提示:
num1和num2的长度都小于 5100num1和num2都只包含数字0-9num1和num2都不包含任何前导零- 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
思路:
大数相加
代码:
class Solution:def addStrings(self, num1: str, num2: str) -> str:res = ""i, j, carry = len(num1) - 1, len(num2) - 1, 0while i >= 0 or j >= 0:n1 = int(num1[i]) if i >= 0 else 0n2 = int(num2[j]) if j >= 0 else 0tmp = n1 + n2 + carrycarry = tmp // 10res = str(tmp % 10) + resi, j = i - 1, j - 1return "1" + res if carry else res
