标签:
题意:连续大数加法,
分析:用c++大整数模板做
1 #include"iostream" 2 #include"cstdio" 3 #include"vector" 4 #include"algorithm" 5 #include"cstring" 6 #include"string" 7 using namespace std; 8 9 struct BigInteger{ 10 static const int BASE=1e8; 11 static const int WIDTH=8; 12 vector<int> s; 13 14 BigInteger(long long num=0){*this=num;} 15 BigInteger operator = (long long num){ 16 s.clear(); 17 do{ 18 s.push_back(num%BASE); 19 num/=BASE; 20 }while(num>0); 21 return *this; 22 } 23 BigInteger operator =(const string &str){ 24 s.clear(); 25 int x,len=(str.length()-1)/WIDTH+1; 26 for(int i=0;i<len;i++){ 27 int end=str.length()-i*WIDTH; 28 int start=max(0,end-WIDTH); 29 sscanf(str.substr(start,end-start).c_str(),"%d",&x); 30 s.push_back(x); 31 } 32 return *this; 33 } 34 BigInteger operator + (const BigInteger& b)const{ 35 BigInteger c; 36 c.s.clear(); 37 for(int i=0,g=0;;i++){ 38 if(g==0&&i>=s.size()&&i>=b.s.size()) break; 39 int x=g; 40 if(i<s.size()) x+=s[i]; 41 if(i<b.s.size()) x+=b.s[i]; 42 c.s.push_back(x%BASE); 43 g=x/BASE; 44 } 45 return c; 46 } 47 bool operator < (const BigInteger& b)const{ 48 if(s.size()!=b.s.size()) return s.size()<b.s.size(); 49 for(int i=s.size()-1;i>=0;i--){ 50 if(s[i]!=b.s[i]) return s[i]>b.s[i]; 51 } 52 return false; 53 } 54 bool operator !=(const BigInteger& b) const{ 55 return b<*this||*this<b; 56 } 57 }; 58 ostream& operator << (ostream &out,const BigInteger& x){ 59 out<<x.s.back(); 60 for(int i=x.s.size()-2;i>=0;i--){ 61 char buf[20]; 62 sprintf(buf,"%08d",x.s[i]); 63 for(int j=0;j<strlen(buf);j++) out<<buf[j]; 64 } 65 return out; 66 } 67 istream& operator >>(istream &in,BigInteger& x){ 68 string s; 69 if(!(in>>s)) return in; 70 x=s; 71 return in; 72 } 73 int main() 74 { 75 BigInteger sum=0,x; 76 while(cin>>x&&x!=0) 77 { 78 sum=sum+x; 79 } 80 cout<<sum<<endl; 81 return 0; 82 }
标签:
原文地址:http://www.cnblogs.com/nuc-gxg/p/5350499.html