【leetcode 简单】 第九十九题 字符串相加

给定两个字符串形式的非负整数 num1num2 ,计算它们的和。

注意:

  1. num1num2 的长度都小于 5100.
  2. num1num2 都只包含数字 0-9.
  3. num1num2 都不包含任何前导零。
  4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
class Solution:
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str

        """
        a,b=len(num1)-1,len(num2)-1
        tmp = 0
        result = ''
        while a>=0 or b>=0:
            if a>=0:
                tmp += ord(num1[a]) - ord('0')
            if b >=0:
                tmp += ord(num2[b]) - ord('0')
            result += chr(tmp%10 + ord('0'))
            tmp //= 10
            a-=1
            b-=1
        if tmp == 1:
            result += '1'
        return result[::-1]

参考:         https://www.polarxiong.com/archives/LeetCode-415-add-strings.html

猜你喜欢

转载自www.cnblogs.com/flashBoxer/p/9545560.html
今日推荐