Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
这道题要求将两个用string表示的数字相加,并且不能使用内置函数和强制转换int。因此我就将其作为字符串来进行处理,每次取两个字符串的最后一位相加,计算结果用其表示的数字的ascii码来保存,carry保存进位,每次将计算出的一位数字转换为对应的char保存进res字符串中,最后逆序输出res字符串。
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
carry = 0
res = ''
i = len(num1) - 1
j = len(num2) - 1
while i >= 0 or j >= 0:
if i >= 0:
carry += ord(num1[i]) - ord("0")
i -= 1
if j >= 0:
carry += ord(num2[j]) - ord("0")
j -= 1
res += chr(carry % 10 + ord("0"))
carry = carry // 10
if carry == 1:
res += '1'
return res[::-1]