首先我们把每一位相乘,得到一个没有进位的临时结果,如图中中间的一行红色数字就是临时结果,然后把临时结果从低位起依次进位。对于一个m位整数乘以n位整数的结果,最多只有m+n位。
例:123*456
1 2 3
4 5 6
----------------------
6 12 18
5 10 15
4 8 12
-------------------------------------------------------
4 13 28 27 18
carry 1 3 2 1 0
---------------------------------------------------------
5 6 0 8 8
注:最后判断数组前几位为0的情况
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0")
return "0";
string res;
int n1 = num1.size(), n2 = num2.size();
vector<int> arr(n1 + n2, 0);
int k = n1 + n2 - 1, carry = 0;
for (int i = 0; i<n1; i++)
for (int j = 0; j<n2; j++)
arr[k - i - j] += (num1[n1-1-i] - '0')*(num2[n2-1-j] - '0');
for (int i = k; i >= 0; i--)
{
arr[i] += carry;
carry = arr[i] / 10;
arr[i] = arr[i]%10;
}
int i = 0;
while(arr[i]==0)i++;
for (; i<arr.size(); i++)
res += (arr[i] + '0');
return res;
}