大数加法
拟人算法系列文章,以容易理解的方式描述算法,点赞收藏不迷路
class Solution:
def solve(self, s: str, t: str) -> str:
res = []
carry = 0
i, j = len(s) - 1, len(t) - 1
while i >= 0 or j >= 0 or carry:
num1 = int(s[i]) if i >= 0 else 0
num2 = int(t[j]) if j >= 0 else 0
total = num1 + num2 + carry
carry = total // 10
res.append(str(total % 10))
i -= 1
j -= 1
return "".join(res[::-1])
if __name__ == '__main__':
s = "163"
t = "456"
print(Solution().solve(s, t)) # "619"
比如两个人在字符串上从尾到头的顺序遍历,只要还有字符串,那么就转换为数字,否则为 0,然后相加,不过加完之后需要考虑进位的数(整除 10),以及当前的数(取 10 的余数),以及最后需要反转结果