56/300
字符串相加 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。 注意: num1 和num2 的长度都小于 5100. num1 和num2 都只包含数字 0-9. num1 和num2 都不包含任何前导零。 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
思路跟02 两数相加 (链表)的相同,食用方法与43 字符串相乘类似,相似题目还有个奇葩的67 二进制求和。
补充:python中 zip截短 zip_longest补长 的使用
class Solution:
def addStrings(self
, num1
: str, num2
: str) -> str:
res
, carry
= '', 0
for n1
, n2
in itertools
.zip_longest
(num1
[::-1],num2
[::-1], fillvalue
= '0'):
n1
, n2
= ord(n1
) - ord('0'), ord(n2
) - ord('0')
total
= n1
+ n2
+ carry
carry
, digit
= divmod(total
, 10)
res
= str(digit
) + res
if carry
: res
= str(carry
) + res
return res