class Solution:
def addtoStrings(self,num1,num2):
# 两个数字字符串相加的结果转为字符串
i, j, add, res = len(num1)-1, len(num2)-1, 0, ''
while i >= 0 or j >= 0 or add != 0:
n1 = int(num1[i]) if i >= 0 else 0
n2 = int(num2[j]) if j >= 0 else 0
tmp = n1 + n2 + add
# 借助除法和取余来得到进位和剩余位数的值
add = tmp // 10
res = str(tmp%10) + res
i -= 1
j -= 1
return res
def compare(self,num1,num2):
# 比较num1和num2的大小 要求num1大于等于num2 这样判断方便后面做减法
if len(num1) > len(num2):
return True
elif len(num2) > len(num1):
return False
else:
# 二者相等 从高位开始比较
for i in range(len(num1)):
if int(num1[i]) < int(num2[i]):
return False
return True
def minustoStrings(self,num1,num2):
# 这里针对 num1大于等于num2的 两个数字字符串相减的结果转为字符串
# num1 减 num2 的字符串结果
i, j, minus, res = len(num1)-1, len(num2)-1, 0, ''
while i >= 0:
n1 = int(num1[i]) if i >= 0 else 0
n2 = int(num2[j]) if j >= 0 else 0
diff = n1 - n2 - minus
if diff < 0:
diff += 10
minus = 1
else:
minus = 0
res = str(diff) + res
i -= 1
j -= 1
for i in range(len(res)):
if res[i] != '0':
return res[i:]
return '0'
def addStrings(self, num1, num2) :
if num1[0] == '-' and num2[0] == '-':
return '-' + self.addtoStrings(num1[1:],num2[1:])
if num1[0] == '-':
# 若num1 更大 则为负 若num2更大则为正
if self.compare(num1[1:],num2):
return '-' + self.minustoStrings(num1[1:],num2)
else:
return self.minustoStrings(num2,num1[1:])
if num2[0] == '-':
# 若num2 更大 则为负 若num1更大则为正
if self.compare(num2[1:],num1):
return '-' + self.minustoStrings(num2[1:],num1)
else:
return self.minustoStrings(num1,num2[1:])
else:
return self.addtoStrings(num1,num2)
num1 = '53'
num2 = '-3'
a = Solution()
print(a.addStrings(num1,num2))