这是一道高精度乘法的模板题。
我们需要模拟列竖式的过程。
Part1
输入两个乘数,将字符转换成数字倒着放入数组中。
cin >> a1 >> b1;
int la = a1.size();
int lb = b1.size();
for(int i = 0;i < la;i++){
a[i] = a1[la - i - 1] - '0';
}
for(int i = 0;i < lb;i++){
b[i] = b1[lb - i - 1] - '0';
}Part2
双重循环,模拟手动列竖式的过程,将答案存入一个数组中。
for(int i = 0;i < lb;i++){
for(int j = 0;j < la;j++){
c[i + j] += a[j] * b[i];
}
}Part3
处理进位,如果当前的值大于九,就向前进位。
for(int i = 0;i < la + lb;i++){
if(c[i] > 9){
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
}Part4
去除前导0。
lc = la + lb;
while(c[lc - 1] == 0 && lc > 1){
lc--;
}Part5
输出 数组即可。
for(int i = lc - 1;i >= 0;i--){
cout << c[i];
}Code
#include<bits/stdc++.h>
using namespace std;
const int N = 1e4;
string a1, b1;
int a[N + 5], b[N + 5], c[N + 5];
int x, la, lb, lc;
int main (){
cin >> a1 >> b1;
int la = a1.size();
int lb = b1.size();
for(int i = 0;i < la;i++){
a[i] = a1[la - i - 1] - '0';
}
for(int i = 0;i < lb;i++){
b[i] = b1[lb - i - 1] - '0';
}
for(int i = 0;i < lb;i++){
for(int j = 0;j < la;j++){
c[i + j] += a[j] * b[i];
}
}
for(int i = 0;i < la + lb;i++){
if(c[i] > 9){
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
}
lc = la + lb;
while(c[lc - 1] == 0 && lc > 1){
lc--;
}
for(int i = lc - 1;i >= 0;i--){
cout << c[i];
}
cout << "\n";
return 0;
}感谢观看。