LeetCode-Python-415. 字符串相加

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

注意:

  1. num1 和num2 的长度都小于 5100.
  2. num1 和num2 都只包含数字 0-9.
  3. num1 和num2 都不包含任何前导零。
  4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

思路:

先排除corner case,

然后调整一下nums1,nums2的相对位置,使得nums1作为两者中较短的那个,

接着把他们倒序转成list,然后从list的头开始加,

加完之后再依次处理进位的问题,这里记得要处理好最后一位进位的情况,记得最后一位进位时,res的长度也要加一,

最后再倒序返回就OK啦。 

class Solution(object):
    def addStrings(self, nums1, nums2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        if not nums1:
            return nums2
        elif not nums2:
            return nums1
        elif not nums1 and not nums2:
            return ""
        
        l1, l2 = len(nums1), len(nums2)
        if l1 > l2: #保证 l1 较短
            l1, l2 = l2, l1
            nums1, nums2 = nums2, nums1
        n1 = list(nums1)[::-1]
        n2 = list(nums2)[::-1]
        
        res = list()
        for i in range(0, l2):
            if i < l1:
                res.append(int(n1[i]) + int(n2[i]))
            else:
                res.append(int(n2[i]))
        
        # print res
        for i in range(0, l2):
            while(res[i] > 9):
                res[i] -= 10
                if i != l2 - 1:
                    res[i + 1] += 1
                else:
                    res.append(1)
                    l2 += 1
                    
        return "".join(str(res[i]) for i in range(l2 - 1, -1, -1))
        
        

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/88431412