高精度乘法
大模拟,直接放代码了,有不对的地方还望可以指正
代码
#include <bits/stdc++.h>
#include <algorithm>
#include <stack>
#define mem(s, i) memset(s, i, sizeof(s))
#define INF 0x3f3f3f3f;
#define ll long long
using namespace std;
char ch1[245], ch2[245];
const int N = 6e5+5;
char ch[N];
int sum[N];//进位数组
stack<int >s;
//记录末尾多余0
int func(char ch[], int l){
int m = 0;
for(int i = l-1;i>=0;i--){
if(ch[i] == '0'){
m++;
}
else break;
}
return m;
}
//判断此时的乘数是否符合为数字
int change(char ch){
if(ch <= '9'&&ch >= '0')return (ch-'0');
else return 0;
}
void solve()
{
mem(ch1,0),mem(ch2,0),mem(ch,0);
scanf("%s %s",&ch1,&ch2);
if(strcmp(ch1,"0")==0||strcmp(ch2,"0")==0){
printf("0\n");
return;
}
//判断末尾是否有多余零,有就更新两个乘数为末尾无多余0的数,并记录有多少0
int l1 = strlen(ch1), l2 = strlen(ch2);
int n1 = func(ch1,l1), n2 = func(ch2,l2);
ch1[l1-n1] = '\0';
ch2[l2-n2] = '\0';
l1 = strlen(ch1), l2 = strlen(ch2);
for(int i = 0;i < l2;i++){
s.push(ch2[i]-'0');
}
int cnt = 0;
int vim1 = 0;
while(!s.empty()){
mem(sum,0);//每一次循环都要把之前的进位归零
int m = s.top();
s.pop();
for(int i = 0,vim = cnt;i < l1;i++,vim++,vim1 = vim){
int n = change(ch[vim]);
ch[vim] = '0'+(m*(ch1[l1-i-1]-'0')+sum[vim]+n)%10;
sum[vim+1] = (m*(ch1[l1-i-1]-'0')+sum[vim]+n)/10;
}
//判断进位数组是否还有未使用的
if(sum[vim1] > 0){
ch[vim1] = '0'+sum[vim1];
}
else{
vim1--;
}
cnt++;
}
for(int i = vim1;i >= 0;i--){
cout<<ch[i];
}
//末尾补0操作
for(int i = 0;i < n1+n2;i++){
cout<<0;
}
}
int main()
{
ios::sync_with_stdio(false);
solve();
return 0;
}