没有什么好说的,照着模板写就是了,稍微用了点手段,支持负数的减法了
1 #include<cstdio> 2 #include<cstring> 3 #include<string> 4 #include<algorithm> 5 #include<vector> 6 #include<iostream> 7 using namespace std; 8 const int maxn=510; 9 struct bigint 10 { 11 int len,s[maxn]; 12 bigint() 13 { 14 len=1; 15 memset(s,0,sizeof(s)); 16 } 17 bigint(int num) 18 { 19 *this=num; 20 } 21 bigint(const char *num) 22 { 23 *this=num; 24 } 25 bigint operator = (int num) 26 { 27 char s[maxn]; 28 sprintf(s,"%d",num); 29 *this=s; 30 return *this; 31 } 32 bigint operator = (const char* num) 33 { 34 len=strlen(num); 35 for(int i=0;i<len;i++) s[i]=num[len-i-1]-‘0‘; 36 return *this; 37 } 38 string str() const 39 { 40 string res=""; 41 for(int i=0;i<len;i++) res=(char)(s[i]+‘0‘)+ res; 42 if(res=="") res="0"; 43 return res; 44 } 45 void clean() 46 { 47 while(len>1 && !s[len-1])len--; 48 } 49 bigint operator + (const bigint &b)const 50 { 51 bigint c; 52 c.len=0; 53 for(int i=0,g=0;g||i<max(len,b.len);i++) 54 { 55 int x=g; 56 if(i<len) x+=s[i]; 57 if(i<b.len) x+=b.s[i]; 58 c.s[c.len++]=x%10; 59 g=x/10; 60 } 61 return c; 62 } 63 bool operator < (const bigint &b)const 64 { 65 if(len!=b.len) return len<b.len; 66 for(int i=len-1;i>=0;i--) 67 { 68 if(s[i]!=b.s[i]) return s[i]<b.s[i]; 69 } 70 return false; 71 } 72 bigint operator - (const bigint &b) 73 { 74 bigint c;c.len=0; 75 for(int i=0,g=0;i<len;i++) 76 { 77 int x=s[i]-g; 78 if(i<b.len) x-=b.s[i]; 79 if(x>=0) g=0; 80 else 81 { 82 g=1; 83 x+=10; 84 } 85 c.s[c.len++]=x; 86 } 87 c.clean(); 88 return c; 89 } 90 bigint operator * (const bigint &b) 91 { 92 bigint c; 93 c.len=len+b.len; 94 for(int i=0;i<len;i++) 95 { 96 for(int j=0;j<b.len;j++) 97 { 98 c.s[i+j]+=s[i]*b.s[j]; 99 } 100 } 101 for(int i=0;i<c.len-1;i++) 102 { 103 c.s[i+1]+=c.s[i]/10; 104 c.s[i]%=10; 105 } 106 c.clean(); 107 return c; 108 } 109 }; 110 istream& operator >> (istream &in,bigint& x) 111 { 112 string s; 113 in>>s; 114 x=s.c_str(); 115 return in; 116 } 117 ostream &operator << (ostream &out,const bigint &x) 118 { 119 out<<x.str(); 120 return out; 121 } 122 int main() 123 { 124 bigint a,b; 125 cin>>a>>b; 126 if(a<b) 127 { 128 cout<<"-"<<b-a; 129 } 130 else 131 { 132 cout<<a-b; 133 } 134 return 0; 135 }
时间: 2024-10-11 20:40:57