字符串相加
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
提示:
num1 和num2 的长度都小于 5100
num1 和num2 都只包含数字 0-9
num1 和num2 都不包含任何前导零
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
自我解答:
很nice, 这题自己做出来了,使用双指针模拟竖式加法进行,因为不能用int强转成数字,可以提前建立一个如{"0":0, "1":1..}这样的字典
def add_strings(num1: str, num2: str) -> str:
nums_map = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}
i = len(num1) - 1
j = len(num2) - 1
sum_num = ""
overflow = 0
while i >= 0 or j >= 0:
s = 0
if i >= 0:
s += nums_map[num1[i]]
i -= 1
if j >= 0:
s += nums_map[num2[j]]
j -= 1
s += overflow
if s >= 10:
s %= 10
overflow = 1
else:
overflow = 0
sum_num = str(s) + sum_num
if overflow:
sum_num = str(overflow) + sum_num
return sum_num
可以优化一下空间:
def add_strings2(num1: str, num2: str) -> str:
nums_map = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}
i, j = len(num1) - 1, len(num2) - 1
sum_num = ""
overflow = 0
while i >= 0 or j >= 0:
s = 0
if i >= 0:
s += nums_map[num1[i]]
i -= 1
if j >= 0:
s += nums_map[num2[j]]
j -= 1
s += overflow
overflow = s // 10
sum_num = str(s % 10) + sum_num
return "1" + sum_num if overflow else sum_num
力扣解答:
可以使用 ASCII, ord("1") - 48 = 1, 这样就能代替字典
def add_strings3(num1: str, num2: str) -> str:
i, j = len(num1) - 1, len(num2) - 1
sum_num = ""
overflow = 0
while i >= 0 or j >= 0:
s = 0
if i >= 0:
s += ord(num1[i]) - 48
i -= 1
if j >= 0:
s += ord(num2[j]) - 48
j -= 1
s += overflow
overflow = s // 10
sum_num = str(s % 10) + sum_num
return "1" + sum_num if overflow else sum_num