高精度算法
高精度加法:
#include<iostream> using namespace std; const int MAXN=500005;//初始化数组 string z,v; int a[MAXN]={0},b[MAXN]={0},ans[MAXN]={0}; void workplus() { cin>>z>>v; long int x=z.length(); long int y=v.length(); for(int i=x-1;i>=0;i--)a[i]=z[x-1-i]-'0'; for(int i=y-1;i>=0;i--)b[i]=v[y-1-i]-'0'; int w=0;w=x>y?x:y; for(int i=0;i<w;i++) { ans[i+1]=(a[i]+b[i]+ans[i])/10; ans[i]=(a[i]+b[i]+ans[i])%10; } bool t=false; for(int i=MAXN-1;i>=0;i--) { if(ans[i]!=0||t==true) { cout<<ans[i]; t=true; } } if(t==false) cout<<0; return; } int main() { workplus(); return 0; }
高精度减法:
#include<iostream> #include<cstring> #include<algorithm> #include<cmath> #include <cstdlib> using namespace std; const int maxn=100001; int l1,l2; int a[maxn],b[maxn]; string s1,s2; void swap(string &a,string &b) { string t; t=a; a=b; b=t; } bool judge(string a,string b) { if(a.size()<b.size())return true; if(a.size()>b.size())return false; for(int i=0;i<a.size();++i) { if(a[i]>b[i])return false; if(a[i]<b[i])return true; } return false; } void work() { cin>>s1>>s2; if(judge(s1,s2)) { swap(s1,s2); cout<<'-'; } l1=s1.size(); l2=s2.size(); for(int i=0;i<=l1;i++)a[l1-i]=s1[i]-'0'; for(int i=0;i<=l2;i++)b[l2-i]=s2[i]-'0';//? for(int i=1;i<=l1;++i) { a[i]-=b[i]; if(a[i]<0) { a[i+1]--; a[i]+=10; } } while(a[l1]==0&&l1>1)l1--; for(int i=l1;i>=1;--i) cout<<a[i]; return; } int main() { work(); return 0; }