python solution:space and time complexity is O(n),and cost 92ms


  • 0
    class Solution(object):
        def addStrings(self,num1,num2):
            ans=''
            if len(num1)<len(num2):
                num1,num2=num2,num1
            dif=len(num1)-len(num2)
            num2='0'*dif+num2
            sum,add=0,0
            for i in range(len(num1)-1,-1,-1):
                n1=num1[i]
                n2=num2[i] if i<len(num2)  else '0'
                sum=int(n1)+int(n2)+add
                add=1 if sum>=10 else 0
                sum=sum-10 if sum>=10 else sum
                ans=str(sum)+ans
            if add==1:
                ans='1'+ans
            return ans if len(ans)>0 else '0'
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.