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
大整數乘法
我們以289*785為例
首先我們把每一位相乘,得到一個沒有進位的臨時結果,如圖中中間的一行紅色數字就是臨時結果,然后把臨時結果從低位起依次進位。對於一個m位整數乘以n位整數的結果,最多只有m+n位。 本文地址
注意:結果中需要去掉前導0,還需要注意結果為0的情況
class Solution {
public:
string multiply(string num1, string num2) {
int n1 = num1.size(), n2 = num2.size();
vector<int> tmpres(n1+n2, 0);
int k = n1 + n2 - 2;
for(int i = 0; i < n1; i++)
for(int j = 0; j < n2; j++)
tmpres[k-i-j] += (num1[i]-'0')*(num2[j]-'0');
int carryBit = 0;
for(int i = 0; i < n1+n2; i++)//處理進位
{
tmpres[i] += carryBit;
carryBit = tmpres[i] / 10;
tmpres[i] %= 10;
}
int i = k+1;
while(tmpres[i] == 0)i--;//去掉乘積的前導0
if(i < 0)return "0"; //注意乘積為0的特殊情況
string res;
for(; i >= 0; i--)
res.push_back(tmpres[i] + '0');
return res;
}
};
上述算法的復雜度為O(n^2)(假設整數長度為n)
另外更高效的計算大整數乘法一般有:(1)karatsuba算法,復雜度為3nlog3≈3n1.585,可以參考百度百科、面試題——大整數乘法、乘法算法-Karatsuba算法。(2)基於FFT(快速傅里葉變換)的算法,復雜度為o(nlogn), 可以參考FFT, 卷積, 多項式乘法, 大整數乘法
【版權聲明】轉載請注明出處:http://www.cnblogs.com/TenosDoIt/p/3735309.html

