地址:http://oj.leetcode.com/problems/multiply-strings/
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.
思路:大数m与n相乘,结果ans的第x位应该是从1. m的第1位与n的第x位
2. m的第2位与n的第x-1位
...
x. m的第x位与n的第1位
上述x个结果求和。
体会一下,这个过程有点像卷积。
注意边界情况,如“0”, “000”这样的相乘。
python参考代码:1196ms
class Solution:
# @param num1, a string
# @param num2, a string
# @return a string
def multiply(self, num1, num2):
if len(num1) < len(num2):
tmp = num2
num2 = num1
num1 = tmp
val = carry = 0
ans = ""
for i in range(0, len(num1)+len(num2)):
for j in range(i+1, 0, -1):
k = i+2-j
if k>len(num2) or j>len(num1):
continue
val += int(num1[-j]) * int(num2[-k])
ans += str((val+carry)%10)
carry = (val+carry)//10
val = 0
while carry>0:
ans += str(carry%10)
carry /= 10
while len(ans)>1 and ans[-1]=="0":
ans = ans[:-1]
return ans[-1::-1]
c++, 52ms
class Solution {public :string multiply ( string num1 , string num2 ) {if ( num1 == "0" || num2 == "0" )return "0" ;if ( num1 == "1" )return num2 ;if ( num2 == "1" )return num1 ;reverse ( num1 . begin (), num1 . end ());reverse ( num2 . begin (), num2 . end ());int sum = 0 , carry = 0 ;string ans ;for ( int i = 0 ; i < num1 . length () + num2 . length (); ++ i ){sum = 0 ;for ( int j = 0 ; j <= i ; ++ j ){if ( j < num1 . length () && i - j < num2 . length ())sum += ( num1 [ j ] - '0' ) * ( num2 [ i - j ] - '0' );}sum += carry ;carry = sum / 10 ;sum %= 10 ;ans += sum + '0' ;}reverse ( ans . begin (), ans . end ());int i = 0 ;for (; i < ans . length (); ++ i )if ( ans [ i ] != '0' )break ;return ans . substr ( i );}};