#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100000;
struct bn
{
int bt[maxn],len;//bt[0]存符号位 0为正,1为负
void clean()//清除前置0
{
while(len>1&&!bt[len])len--;
}
bn operator = (const string& s)
{
memset(bt,0,sizeof(bt));
if(s[0]=='-') bt[0]=1;
len=s.length()-bt[0];
for(int i=1;i<=len;i++){
bt[i]=s[len-i+bt[0]]-'0';//倒着存
}
clean();
return *this;
}
bn operator + (bn& b)//加减法写在一起
{
bn c=*this;
if(c.bt[0]==b.bt[0])//两数同号,都是加法,符号不变
{
c.len=max(c.len,b.len);
for(int i=1;i<=c.len;i++)//每一位相加,大于10的进位
{
c.bt[i]+=b.bt[i];
c.bt[i+1]+=c.bt[i]/10;
c.bt[i]%=10;
}
if(c.bt[c.len+1]!=0)c.len++;
}
else
{
if(c.len<b.len||c.len==b.len&&c.bt[len]<b.bt[len])//如果c比b小
{
c.bt[0]=1;
bn t=c;c=b;b=t;//交换两数
}
for(int i=1;i<=c.len;i++)
{
if(c.bt[i]<b.bt[i])//借位
{
c.bt[i+1]--;
c.bt[i]+=10;
}
c.bt[i]-=b.bt[i];
}
c.clean();//不能直接clean
}
return c;
}
bn operator * (const bn& b)
{
bn c;
if(bt[0]==b.bt[0])c.bt[0]=0;
else c.bt[0]=1;
c.len=len+b.len;//两个符号位要舍去一个
for(int i=1;i<=len;i++)
for(int j=1;j<=b.len;j++)
c.bt[i+j-1]+=bt[i]*(b.bt[j]);//两个符号位要舍去一个
for(int i=1;i<c.len;i++)
{
c.bt[i+1]+=c.bt[i]/10;
c.bt[i]%=10;
}
c.clean();
return c;
}
};
istream& operator >>(istream& in,bn& x)//重载
{
string s;
in>>s;
x=s.c_str();
return in;
}
ostream& operator << (ostream& out,const bn& x)
{
if(x.bt[0]==1)out<<"-";
for(int i=x.len;i>0;i--)
out<<x.bt[i];
return out;
}
int main()
{
bn a,b,c;
cin>>a>>b;
c=a+b;
cout<<c<<endl;
c=a*b;
cout<<c;
return 0;
}
高精度模版
最新推荐文章于 2023-09-30 11:15:33 发布