逐位相乘处理进位法
乘积是逐位相乘,也就是aibjaibj,结果加入到积c的第i+j位,最后处理进位即可:
举例:
A=13,B=19
a=(3,1),b=(9,1)
c=(3∗9,3∗1+1∗9,1∗1)=(27,12,1)=(7,14,1)=(7,4,2)
C=247
因此,思路是:
- 字符串反转;
- 逐位相乘,结果存放在v[i+j]中;
- 处理进位,结果存放在v[i+j]中;
- 将计算结果转换为字符串并反转。
C++代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main(int argc, char const* argv[])
{
string s1, s2;
while (cin >> s1 >> s2) {
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
vector<int> v(s1.size() + s2.size(), 0);
for (int i = 0; i < s1.size(); i++) {
for (int j = 0; j < s2.size(); j++) {
v[i + j] += (s1[i] - '0') * (s2[j] - '0');
}
}
for (int i = 0; i < v.size() - 1; i++) {
if (v[i] >= 10) {
v[i + 1] += v[i] / 10;
v[i] %= 10;
}
}
string res;
int i;
for (i = v.size() - 1; i > 0 && v[i] == 0; i--);
for (; i >= 0; i--) {
res += (char)(v[i] + '0');
}
cout << res << endl;
}
system("pause");
return 0;
}
C++代码详解(代码和上面相同,只是加了注释):
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
/*
举例:
A = 13,B = 19
a = (3, 1), b = (9, 1)
c = (3∗∗9, 3∗∗1 + 1∗∗9, 1∗∗1) = (27, 12, 1) = (7, 14, 1) = (7, 4, 2)
C = 247
*/
int main(int argc, char const* argv[])
{
string s1, s2;
while (cin >> s1 >> s2) {
// 字符串反转
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
// v 保存计算后的结果
vector<int> v(s1.size() + s2.size(), 0);
// 逐位相乘
for (int i = 0; i < s1.size(); i++) {
for (int j = 0; j < s2.size(); j++) {
v[i + j] += (s1[i] - '0') * (s2[j] - '0');
}
}
// 处理进位
for (int i = 0; i < v.size() - 1; i++) {
if (v[i] >= 10) { // 如果值大于等于10,则处理进位
v[i + 1] += v[i] / 10;
v[i] %= 10;
}
}
string res;
int i;
// 将计算结果转换成字符串并反转
for (i = v.size() - 1; i > 0 && v[i] == 0; i--); // 消除多余的0
for (; i >= 0; i--) {
res += (char)(v[i] + '0');
}
cout << res << endl;
}
system("pause");
return 0;
}