之前做的大整数,都是一位一位操作。

优化方案:压缩方案。

模板: + - *  操作符重载

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
using namespace std; struct bigint{ // only positive number;
static const int BASE=;
static const int WIDTH=;
vector<int> s;
//value
bigint(long long num=){ *this = num;}
bigint operator = (long long num){
s.clear();
do{
s.push_back(num%BASE);
num/=BASE;
}while(num>);
return *this;
}
bigint operator = (const string& str){
s.clear() ;
int x,len = (str.length()-)/WIDTH + ;
for(int i=;i<len;i++){
int end = str.length() - i*WIDTH;
int start = max(,end - WIDTH);
sscanf(str.substr(start,end-start).c_str(),"%d",&x);
s.push_back(x);
}
return *this;
}
//input&output
friend ostream& operator << (ostream &out, const bigint& x){
out << x.s.back();
for(int i=x.s.size()-;i>=;i--){
char buf[];
sprintf(buf,"%08d",x.s[i]);
for(int j=;j<strlen(buf);j++) out << buf[j];
}
return out;
}
friend istream& operator >>(istream &in, bigint& x){
string s;
if(!(in>>s)) return in;
x=s;
return in;
}
//compare
bool operator < (const bigint& b) const {
if(s.size()!=b.s.size()) return s.size() < b.s.size();
for(int i=s.size()-;i>=;i++) if(s[i]!=b.s[i]) return s[i] < b.s[i];
return false;//equal
}
bool operator > (const bigint& b) const {return b < *this;}
bool operator <= (const bigint& b) const {return !(b < *this);}
bool operator >= (const bigint& b) const {return !(*this < b);}
bool operator != (const bigint& b) const {return b < *this || *this < b;}
bool operator == (const bigint& b) const {return !(b < *this) && !(*this < b);}
//calculate
bigint operator +(const bigint& b) const {
bigint c;
c.s.clear();
for(int i=,g=;;i++){
if(g== && i>=s.size() && i>=b.s.size()) break;
int x=g;
if(i<s.size()) x+=s[i];
if(i<b.s.size()) x+=b.s[i];
c.s.push_back(x%BASE);
g = x/BASE;
}
return c;
}
bigint operator +=(const bigint& b){
*this = *this + b;
return *this;
}
bigint operator -(const bigint& b) const {
bigint c;
c.s.clear();
for(int i=,g=;;i++){
if(g== && i>=s.size() && i>=b.s.size()) break;
int x=g;
if(i<s.size()) x+=s[i];
if(i<b.s.size()) x-=b.s[i];
x+=BASE;
c.s.push_back(x%BASE);
g = x/BASE - ;
}
return c;
}
bigint operator * (const bigint& b) const {
bigint c;
c.s.clear();
bigint g=;
for(int i=;;i++){
if(g.s.size()== && i>=s.size()+b.s.size()-) break;
bigint x;
x.s.clear() ;
for(int j=;j<g.s.size();j++) x.s.push_back(g.s[j]);
if(i<s.size()+b.s.size()-){
for(int j = max( , i-(int)s.size()+);j<=min(i,(int)b.s.size()-);j++){
bigint t = (long long)b.s[j]*s[i-j];
x += t;
}
}
c.s.push_back(x.s[]);
g.s.clear();
if(x.s.size()>) for(int j=;j<x.s.size();j++) g.s.push_back(x.s[j]);
}
return c;
}
}; int main()
{
//freopen("in.txt","r",stdin);
bigint a;
bigint b = ;
bigint sum = ; while(cin>>a) {
if(a==)
break;
sum +=a;
} cout<< sum <<endl; return ;
}
05-28 12:38