大整数类主要就是运算符的重载问题,除<<和>>外其他的符号都要写在struct的外面,而且只要定义了一个<符号之后,其它的符号都可以根据<的关系推导出来
下面贴上代码
注意给字符串赋值的时候,如果声明就开始赋值,那么必须得定义一个函数BigInteger(string/char[]/long long)
#include<vector> #include<iostream> #include<string> #include<cstdio> using namespace std; struct BigInteger { static const int WIDTH = 8; static const int BASE = 100000000;//千万级别 vector<int>s; BigInteger(long long num = 0){*this = num;}//构造函数,其中的=号,需要等会重载一下 BigInteger(string str){*this = str;} BigInteger operator = (long long num) { s.clear(); do { s.push_back(num % BASE); num = num / BASE; }while(num); return *this; } BigInteger operator = (string str) { s.clear(); int start = str.length(),last = str.length(); do { int x; start = max(start - WIDTH,0); sscanf(str.substr(start,last-start).c_str(),"%d",&x);//特别注意:substr的第二个参数是从start开始的有多少个字符 s.push_back(x); last = start; }while(start); return *this; } BigInteger operator + (BigInteger B) { BigInteger c; c.s.clear(); int g = 0; for(int i=0,j=0;j<B.s.size()||i<this->s.size()||g;i++,j++) { if(i<s.size()) { g=g+s[i]; } if(j<B.s.size()) { g=g+B.s[j]; } c.s.push_back(g%BASE); g=g/BASE; } return c; } void output() { for(int i=s.size()-1;i>=0;i--) { cout<<s[i]; } } bool operator < (BigInteger B) { if(s.size() < B.s.size()) return true; if(s.size() > B.s.size()) return false; for(int i = s.size() - 1;i >= 0;i--) { if(s[i] < B.s[i]) return true; if(s[i] > B.s[i]) return false; } return false;//相等 } bool operator > (BigInteger B) { if(B < *this) return true; return false; } bool operator <= (BigInteger B) { if(*this > B) { return false; } return true; } bool operator >= (BigInteger B) { if(*this < B) return false; return true; } bool operator == (BigInteger B) { if(*this > B) return false; if(*this < B) return false; return true; } bool operator != (BigInteger B) { if(*this == B) { return false; } else { return true; } } }; ostream& operator << (ostream &out, BigInteger B) { for(int i=B.s.size()-1;i>=0;i--) { cout<<B.s[i]; } return out; } istream& operator >> (istream &in, BigInteger B) { string s; if(!(in>>s))return in; B=s; return in; } int main() { vector<BigInteger>V; BigInteger x("1234567890123456789012345678901234567890"); BigInteger y("9876543210987654321"); BigInteger z("3426245"); BigInteger G("3426245"); V.push_back(x); V.push_back(y); V.push_back(z); if(x>=y)printf(">=\n"); if(y<=y)printf("<=\n"); if(z==G)printf("<=\n"); if(x!=y)printf("!=\n"); x.output(); return 0; }