给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
注意:
num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-strings
题解:根据题意不能使用BigInteger库,所以一般的字符串运算方法eval()就不能使用了,所以这里我们可以参照一般加法原则,从尾部依次相加然后记录进位的个数,最后再根据是否需要进位再加一。
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
carry = 0
tmp = 0
res = ""
n1 = len(num1) - 1
n2 = len(num2) - 1
while n1 >= 0 or n2 >= 0:
i = int(num1[n1]) if n1 >= 0 else 0
j = int(num2[n2]) if n2 >= 0 else 0
carry = (i + j + tmp) % 10
tmp = (i + j + tmp) // 10
res = str(carry) + res
n1 -= 1
n2 -= 1
return "1" + res if tmp else res