欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Add Strings

程序员文章站 2022-06-04 10:58:59
...

Add Strings

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note

The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

Solution

class Solution:
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        list_num = [0]*(max(len(num1), len(num2))+1)
        num1 = num1[::-1]
        num2 = num2[::-1]
        ret = ''
        carry = 0
        for i in range(max(len(num1), len(num2))+1):
            a = int(num1[i]) if i<len(num1) else 0
            b = int(num2[i]) if i<len(num2) else 0           
            digit = (a+b+carry)%10
            carry = (a+b+carry)//10
            list_num[i] = digit
        list_num.reverse()
        for num in list_num:
            ret += str(num)
        if ret[0]=='0':
            ret = ret[1::]
        return ret
相关标签: leetcode python