My solution for your reference.


  • -1
    L

    a straight forward solution.

    class Solution:
    
    def addTwo(self,a,b):
        carry=0;
        res='';
        while(len(a) or len(b) or carry==1):
            sum=carry;
            if(len(a)):
                sum+=int(a[-1]);
            if(len(b)):
                sum+=int(b[-1]);
    
            if(sum>=10):
                sum=sum-10;
                carry=1;
            else:
                carry=0;
            a,b=a[0:-1],b[0:-1];
            res=str(sum)+res;
        
        return res;
    
    # @param num1, a string
    # @param num2, a string
    # @return a string
    def multiply(self, num1, num2):
        def multiplyTwo(num1,i2,scale):
            if(i2==0):
                return num1+"0"*scale;
            else:
                ret="";
                carry=0;
                for i in range(len(num1)-1,-1,-1):
                    i1=int(num1[i]);
                    mul= i1*i2+carry;
                    ret=str(mul %10)+ret;
                    carry=mul//10;
                if(carry!=0):
                    ret=str(carry)+ret;
                return ret+"0"*scale;
        
        if(num1=="0" or num2=="0" or len(num1)<=0 or len(num2)<=0):
            return "0";
        else:
            str1,str2=num1,num2;
            if(len(num1)<len(num2)):
                str1,str2=num2,num1;
            
            total="0";
            for i in range(len(str2)-1,-1,-1):
                total=self.addTwo(total,multiplyTwo(str1,int(str2[i]),len(str2)-1-i));
    
            return total;

Log in to reply
 

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