415.Add Strings

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.

Solution1:

class Solution:
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        return str(int(num1)+int(num2))

python3的int是没有大小限制的。

Solution2:

class Solution:
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        num1 = list(num1)[::-1]
        num2 = list(num2)[::-1]
        i,j = 0,0
        while i<len(num1) and j<len(num2):
            num1[i] = str(int(num1[i]) + int(num2[i]))
            i += 1
            j += 1
        # print('num1:',num1)
        # print('num2:',num2)
        # print('i=',i)
        # print('j=',j)
        while j<len(num2):
            num1.append(num2[j])
            j += 1
        carry = 0
        for i in range(len(num1)-1):
            num1[i] = str(int(num1[i]) + carry)
            if int(num1[i])>9:
                num1[i] = str(int(num1[i])-10)
                carry = 1
            else:
                carry = 0
        # print('carry:',carry)
        # print(num1[::-1])
        num1[-1] = str(int(num1[-1]) + carry)
        # print(num1[::-1])
        if int(num1[-1])>9:
            num1[-1] = str(int(num1[-1]) - 10)
            num1.append('1')
        return ''.join(num1[::-1])
原文地址:https://www.cnblogs.com/bernieloveslife/p/9765651.html