415. 字符串相加
描述
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
注意:
num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
我
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
flag = 0
if len(num1) > len(num2):
short = num2
long = num1
elif len(num1) == len(num2):
flag = 1
short = num2
long = num1
else:
short = num1
long = num2
in_count = 0
result = ''
for i in range(len(short)-1, -1, -1):
temp = ord(short[i]) + ord(long[i+len(long)-len(short)]) - 48 * 2
temp += in_count
if temp > 19:
in_count = 2
temp -= 20
elif temp > 9:
in_count = 1
temp -= 10
else:
in_count = 0
result += str(temp)
if flag == 1:
if in_count:
result += str(in_count)
result = result[::-1]
else:
j = len(long) - len(short)
if in_count:
for j in range(len(long)-len(short)-1,-1,-1):
temp = ord(long[j]) + in_count - 48
if temp > 9:
in_count = 1
temp -= 10
result += str(temp)
else:
result += str(temp)
in_count = 0
result = long[0:j] + result[::-1]
break
if in_count:
result = '1' + result[::-1]
else:
result = long[0:j] + result[::-1]
return result
总结一下:
这题涉及到的逻辑判断较多。。所以我目前还是有点混乱,调试了五次一个小时才成功通过。。。昨天还想嘲讽leetcode,今天不敢了。
解题方法就是将字符转换为ASCII码做运算。。。。。。其实跟转为int没啥区别我觉得,但我想不出其他方法来,还是太菜