代码改变世界

[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:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. 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]