高精度运算模板(加、减)
1.高精度加法:
#include<bits/stdc++.h>//10^500
using namespace std;
int a[501],b[501],c[501],l1,l2;
string s1,s2,s;
string jia(string s1,string s2)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
string ans;
for(int i=1;i<=l1;i++)a[i]=s1[l1-i]-'0';
for(int i=1;i<=l2;i++)b[i]=s2[l2-i]-'0';
int l3=1;
while(l1>0||l2>0||c[l3+1])
{
c[l3]+=a[l3]+b[l3];
c[l3+1]+=c[l3]/10;
c[l3]%=10;
l3++;
l1--;
l2--;
}
while(c[l3]==0&&l3>1)l3--;
for(;l3>=1;l3--)ans+=c[l3]+'0';
return ans;
}
int main()
{
cin>>s1>>s2;
l1=s1.size();
l2=s2.size();
s=jia(s1,s2);
cout<<s<<endl;
return 0;
}
2.高精度减法
#include<bits/stdc++.h>//10^10086
using namespace std;
int a[10089],b[10089],c[10089],l1,l2,f;
string s1,s2,s;
string jian(string s1,string s2)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
string ans;
for(int i=1;i<=l1;i++)a[i]=s1[l1-i]-'0';
for(int i=1;i<=l2;i++)b[i]=s2[l2-i]-'0';
int l3=1;
while(l1>0)
{
c[l3]=a[l3]-b[l3];
if(c[l3]<0)a[l3+1]--,c[l3]+=10;
l3++;
l1--;
}
while(c[l3]==0&&l3>1)l3--;
for(;l3>=1;l3--)ans+=c[l3]+'0';
return ans;
}
void check()
{
if(l2>l1||l1==l2&&l1<l2)
{
string ss=s1;s1=s2;s2=ss;
int l=l1;l1=l2;l2=l;
f=1;
return ;
}
}
int main()
{
cin>>s1>>s2;
l1=s1.size();
l2=s2.size();
check();
s=jian(s1,s2);
if(f==1)cout<<'-';
cout<<s<<endl;
return 0;
}