[LeetCode] 415. Add Strings_Easy tag: String
2018-08-13 04:21 Johnson_强生仔仔 阅读(256) 评论(0) 编辑 收藏 举报Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
这个题目跟[LeetCode] 67. Add Binary_Easy tag: String思路一致, 先将length补齐, 然后进位, 最后判断edge case, 如果有进位的处理, 然后这里用ord(a[i]) - ord('0') 转换integer.
Code
class Solution: def addStrings(self, num1, num2): m, n = len(num1), len(num2) if m > n: num1, num2, m, n = num2, num1, n, m num1, pre, ans = '0'*(n-m) + num1, 0, "" for i in range(n)[::-1]: pre, rem = divmod(ord(num1[i]) + ord(num2[i]) - 2* ord('0') + pre, 10) ans += str(rem) return ans[::-1] if not pre else '1' + ans[::-1]