Problem Definition:
Given numbers represented as strings, return multiplication of the numbers as a string.
Note:the numbers can be arbitrarily large and is non-negative.
Solution:
Large number multiplication, commonly used algorithms are: Long multiplication, divide the rule, the FFT.
1) Bitwise multiplication.
1 #@param {string} num12 #@param {string} num23 #@return {string}4 defMultiply (self, NUM1, num2):5 ifnum1=='0' ornum2=='0':6 return '0'7Num1,num2=map (int, NUM1), map (int, num2)8N1,n2=Len (NUM1), Len (num2)9result=[0]* (n1+n2)Ten forIinchRange (N1-1,-1,-1): Onecarry=0 A forJinchRange (n2-1,-1,-1): -Pz= (n1-1-i) + (n2-1-j) -result[pz]+=carry+num1[i]*Num2[j] theCarry=result[pz]/10 -result[pz]%=10 -result[n1-1-i+n2]+=Carry - + whileresult[-1]=='0': - Result.pop () + return "'. Join (Map (str, result[::-1))
2) Group multiplication. A 64-bit binary number can express a 19-bit decimal number, so the product of two 9-bit decimal numbers can be stored with a 64-bit binary number without overflow.
So it is possible to put large integers represented by arrays, each 9 bits in a group, and then multiply them group-by-group, faster than Digit-by-digit. To preprocess, group the digits.
1 #@param {string} num12 #@param {string} num23 #@return {string}4 defMultiply (self, NUM1, num2):5 #Convert number string into List of 9-digit numbers6 def_convert2list (numstring):7Numlist = [0] * (len (numstring) + 8)//9)8 #store 9-digit number in reverse order9NUMLIST[0] = Int (numstring[-9:])Ten forIndexinchRange (1, Len (numlist)): OneNumlist[index] = Int (numstring[-(index+1) *9:-index*9]) A returnnumlist - - #multiply a number list with a in most 9-digit multiplier the def_multiplysingle (result, start, numlist, multiplier): -carry =0 - forIndexinchRange (len (numlist)): -Resultindex = index +Start +Carry + = (Numlist[index] * multiplier) +Result[resultindex] -Carry, Result[resultindex] = Divmod (Carry, 1000000000) +Result[len (numlist) + start] =Carry A at ifNUM1 = ='0' orNum2 = ='0': - return '0' - #convert string to Integer -Num1list, num2list =_convert2list (NUM1), _convert2list (num2) -result = [0] * (len (NUM1) + len (num2) + 16)//9) - forIndexinchRange (len (num2list)): in _multiplysingle (result, index, num1list, Num2list[index]) - to #remove leading 0s + whileRESULT[-1] = =0: - Result.pop () the #Convert to String * returnSTR (result[-1]) +"'. Join (Map (LambdaX:string.zfill (x, 9), result[:-1][::-1]))
Actually write directly
return str (int (NUM1) *int (num2))
can also be passed, because Python itself has a mechanism for handling overflow. int is automatically converted to long, and long is a large integer type, which limits its length to memory size.
leetcode#43 Multiply Strings