Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
解题思路:
1. 为防止溢出,大数相乘以字符串保存相乘结果;
2. 假设被乘数为 a,乘数为 b ,求 a * b;
3. 假设某一时刻,b 的第 0 至 i-1 位乘 a 的结果已经获得,保存在 tmp 当中;
4. 以 b 的第 i 位乘以 a 的第 0 位,相乘结果对 10 取余获得该位的乘法结果,对 10 取整获得向高位的乘法进位;
5. 取上一步中的乘法结果和 tmp 中的第 i 位相加,对 10 取余获得该位的本次相乘结果(tmp 得到更新),对 10 取整获得向高位的加法进位;
6. 直至将 b 的每一位和 a 相乘完成;
7. 以相乘完成后乘法进位和加法进位的和作为 tmp 的最高位(b 的第 i 位乘完 a 的最高位后可能会有进位并且这个进位最大为 8 (9*9=81),同时上一步的加法也可能会产生进位并且这个进位最大为 1,所以这两个进位和最大为 9 ,不会再产生新的进位);
8. 以新的 tmp 作为 b 的第 0 至第 i 位乘以 a 的结果;
9. 重复以上步骤直至乘完 b 的所有位。
完整代码:
#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <set>
using namespace std;
class Solution {
public:
string multiply(string num1, string num2) {
int last = 3*3-1;
string ret(last+1,'0');
int i = num2.size()-1 ;
while(i >= 0)
{
int propro = 0;
int proadd = 0;
int j = num1.size()-1;
int cur = last-(num2.size()-i-1);
while(j >= 0 )
{
char c = (((num2[i]-'0') * (num1[j] - '0')) + propro)%10 +'0';
propro = (((num2[i]-'0') * (num1[j] - '0')) + propro)/10;
char tmp = ret[cur];
ret[cur] = (c - '0' + tmp - '0' + proadd)%10 + '0';
proadd = (c - '0' + tmp - '0' + proadd)/10;
cur--;
j--;
}
if(propro+proadd != 0)
ret[cur] = (propro+proadd)+'0';
i--;
}
int k = 0;
while(ret[k] == '0')k++;
if(ret.substr(k,last+1).size() == 0)
return "0";
return ret.substr(k,last+1);
}
};
void main()
{
string num1;
string num2;
cin >> num1;
cin >> num2;
Solution s;
cout << s.multiply(num1,num2) << endl;
}