[leetcode: Python]415. Add Strings

Title
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.

大数问题
方法一:102ms

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """

        l1 = len(num1)
        l2 = len(num2)
        lm = max(l1, l2)
        num1 = num1.zfill(lm)
        num2 = num2.zfill(lm)
        num1 = num1[::-1]
        num2 = num2[::-1]

        s = []
        c = 0
        for i in range(lm):
            sum1 = int(num1[i]) + int(num2[i]) + c
            c, sum1 =divmod(sum1, 10)
            s.append(str(sum1))
        l = s[::-1]
        s1 = ''.join(l)
        if c == 1:
            s1 = '1' + s1
        if  len(s1) == 1:
            return l[0]
        return s1

方法二:78ms

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        t1 = 0
        for i in num1:
            t1 *= 10
            t1 += ord(i) - 48


        t2 = 0
        for i in num2:
            t2 *= 10
            t2 += ord(i) - 48

        return str(t1 + t2)

你可能感兴趣的:(LeetCode:,Easy)