BigInteger之高精度加法
struct BigInteger
struct BigInteger { static const int BASE = 100000000; static const int WIDTH = 8; vector<int> s; };
重写“=”
BigInteger operator = (const string& str) { s.clear(); int x,len = (str.length()-1)/WIDTH +1; for(int i =0; i<len; i++) { int end = str.length() - i*WIDTH; int start = max(0,end-WIDTH); sscanf(str.substr(start,end-start).c_str(),"%d",&x); s.push_back(x); } return *this; }
重写“+”
BigInteger operator + (const BigInteger& b){ BigInteger c; c.s.clear(); for(int i=0,g=0;;i++){ if(g==0&& 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; }
重写iostream
ostream& operator << (ostream &out,const BigInteger& x) { BigInteger c; c = x; while(c.s.end()-1!=c.s.begin()){//去掉高位的0 if(c.s.back()==0) c.s.pop_back(); else break; } out<<c.s.back(); for(int i=c.s.size()-2; i>=0; i--) { char buf[20]; sprintf(buf,"%0*d",BigInteger::WIDTH,c.s[i]); for(int j=0; j<strlen(buf); j++) out<<buf[j]; } return out; } istream& operator >> (istream &in,BigInteger& x){ string s; if(!(in>>s))return in; x = s; return in; }
高精度加法源代码
1 #include <iostream> 2 #include <cstring> 3 #include <vector> 4 #include<stdio.h> 5 using namespace std; 6 struct BigInteger { 7 static const int BASE = 100000000; 8 static const int WIDTH = 8; 9 vector<int> s; 10 BigInteger operator = (const string& str) { 11 s.clear(); 12 int x,len = (str.length()-1)/WIDTH +1; 13 for(int i =0; i<len; i++) { 14 int end = str.length() - i*WIDTH; 15 int start = max(0,end-WIDTH); 16 sscanf(str.substr(start,end-start).c_str(),"%d",&x); 17 s.push_back(x); 18 } 19 return *this; 20 } 21 BigInteger operator + (const BigInteger& b){ 22 BigInteger c; 23 c.s.clear(); 24 for(int i=0,g=0;;i++){ 25 if(g==0&& i>=s.size()&&i>=b.s.size()) break; 26 int x = g; 27 if(i< s.size())x+=s[i]; 28 if(i<b.s.size())x+=b.s[i]; 29 c.s.push_back(x%BASE); 30 g = x/BASE; 31 } 32 return c; 33 } 34 }; 35 36 ostream& operator << (ostream &out,const BigInteger& x) { 37 BigInteger c; 38 c = x; 39 while(c.s.end()-1!=c.s.begin()){ 40 if(c.s.back()==0) c.s.pop_back(); 41 else break; 42 } 43 out<<c.s.back(); 44 for(int i=c.s.size()-2; i>=0; i--) { 45 char buf[20]; 46 sprintf(buf,"%0*d",BigInteger::WIDTH,c.s[i]); 47 for(int j=0; j<strlen(buf); j++) 48 out<<buf[j]; 49 } 50 return out; 51 } 52 istream& operator >> (istream &in,BigInteger& x){ 53 string s; 54 if(!(in>>s))return in; 55 x = s; 56 return in; 57 } 58 59 int main() { 60 BigInteger a ; 61 BigInteger b; 62 BigInteger c; 63 cin>>a>>b; 64 c = a+b; 65 cout<<c<<endl; 66 return 0; 67 }