大整数乘法,模拟草稿手算过程,注意做好进位处理即可。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string mul(string a, string b) {
if (a.size() < b.size()) swap(a, b);
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string res;
for (size_t i = 0; i < b.size(); i++) {
int carryIn = 0;
for (size_t j = 0; j < a.size(); j++) {
if (i+j < res.size()) {
char ck = (b[i] - ‘0‘) * (a[j] - ‘0‘)
+ (res[i+j] - ‘0‘) + carryIn;
carryIn = ck / 10;
res[i+j] = ck % 10 + ‘0‘; // 到这里自然就知道上面的if条件了
} else {
char ck = (b[i] - ‘0‘) * (a[j] - ‘0‘)
+ carryIn;
carryIn = ck / 10;
res.push_back(ck % 10 + ‘0‘);
}
}
while (carryIn) {
res.push_back(carryIn % 10 + ‘0‘);
carryIn /= 10;
}
}
reverse(res.begin(), res.end());
return res;
}
int main() {
string a, b;
cin >> a >> b;
cout << mul(a, b) << endl;
return 0;
}