题解 | #大数加法#
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
class Solution: def solve(self , s: str, t: str) -> str: if not s: return t if not t: return s if len(s) < len(t): s, t = t, s flag = 0 i = len(s)-1 while i >= 0: tmp = ord(s[i]) - ord('0') + flag j = i - len(s) + len(t) if j >= 0: tmp += ord(t[j]) - ord('0') flag = tmp // 10 tmp = tmp%10 s = s[:i] + chr(tmp+ord('0'))+s[i+1:] i -= 1 if flag == 1: s = "1" + s return s
解题思路
- 先判断字符串是否为空,为空则返回另外一个字符串;
- 将s作为长的那个字符串,t作为短的那个字符串;
- 以长的字符串为下标索引开始循环:
- 先让长字符的元素加上flag;
- 然后判断当前短字符串是否遍历完成,如果没有,就再加上短字符串元素的值;
- 之后判断根据和计算一下商和余数,得到结果位的值以及进位值;
- 之后进行赋值,完成当前位的计算。
4. 循环结束之后,如果还有进位,就在字符串最前面加一个“1”。
复杂度
时间复杂度为O(N),空间复杂度为O(1)。