大数加法 -- 每日一题01
题目:以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。示例:输入:"1","99"输出:"100"
数据范围:,字符串仅由'0'~‘9’构成
要求:时间复杂度
思路:想起来小学学数学,如99+11,先取末尾的9和1,9+1=10,进1取0,再取下一个9和1加刚刚进位上来的1,即
9+1+1=11,取1进1,之后就没什么取的了,之前三步取上来的 1 1 0,就是结果110
代码:
class Solution:
def solve(self, s: str, t: str) -> str:
# write code here
s_list = list(s)
t_list = list(t)
next = 0
res = []
while len(s_list) > 0 and len(t_list) > 0:
pop_num = int(s_list.pop()) + int(t_list.pop()) + next
if pop_num >= 10:
next = 1
else:
next = 0
pop_num = str(pop_num)
res.append(pop_num[len(pop_num)-1])
if len(s_list) == 0 and len(t_list) == 0:
if next == 1:
res.append('1')
res.reverse()
return ''.join(res)
if len(t_list) == 0:
while len(s_list) > 0:
add_num = next + int(s_list.pop())
if add_num >= 10:
next = 1
else:
next = 0
add_num = str(add_num)
res.append(add_num[len(add_num)-1])
if len(s_list) == 0:
while len(t_list) > 0:
add_num = next + int(t_list.pop())
if add_num >= 10:
next = 1
else:
next = 0
add_num = str(add_num)
res.append(add_num[len(add_num)-1])
if next == 1:
res.append('1')
res.reverse()
return ''.join(res)
查看5道真题和解析