Given two numbers represented as strings, return multiplication of the numbers as a string.
Note:
The numbers can be arbitrarily large and are non-negative.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
# Sol1: TLE on large intclassSolution(object):defmultiply(self,num1,num2):""" :type num1: str :type num2: str :rtype: str """mid_result=[]# calculate each digit of num2 * num1num1=num1[::-1]num2=num2[::-1]ifnum1=="0"ornum2=="0":return"0"foriinnum2:carry=0result=""forjinnum1:val=int(i)*int(j)+carrycarry=val/10result=str(val%10)+resultifcarry!=0:result=str(carry)+resultmid_result.append(result[:])n=len(mid_result)result=mid_result[0]foriinrange(1,n):result=self.add_string(result,mid_result[i]+"0"*i)returnresultdefadd_string(self,s1,s2):i=len(s1)-1j=len(s2)-1carry=0ret=""whilei>=0orj>=0:ifi>=0andj>=0:val=int(s1[i])+int(s2[j])+carryi-=1j-=1elifi>=0:val=int(s1[i])+carryi-=1else:#j>=0:val=int(s2[j])+carryj-=1carry=val/10ret=str(val%10)+retifcarry!=0:ret=str(carry)+retreturnret# Sol2classSolution:# @param num1, a string# @param num2, a string# @return a stringdefmultiply(self,num1,num2):num1=num1[::-1];num2=num2[::-1]arr=[0foriinrange(len(num1)+len(num2))]foriinrange(len(num1)):forjinrange(len(num2)):arr[i+j]+=int(num1[i])*int(num2[j])ans=[]foriinrange(len(arr)):digit=arr[i]%10carry=arr[i]/10ifi<len(arr)-1:arr[i+1]+=carryans.insert(0,str(digit))whileans[0]=='0'andlen(ans)>1:delans[0]return''.join(ans)if__name__=="__main__":sol=Solution()printsol.multiply("98","9")