Package Big Int Number Class
高精度整形数封装类。
操作符<<和>>注意使用友元标记,否则编译错误。
#include <iostream> #include <string> #include <vector> using namespace std; struct bign { vector<short> num; bign() { num.push_back(0); } bign(const char* str) { *this = str; } bign &operator = (const char* str) { string s = str; num.clear(); for (int i=s.size()-1; i>=0; --i) { char c = s[i]; num.push_back(c - '0'); } return *this; } bign operator + (const bign &n) const { bign tmp; tmp.num.clear(); int a = num.size(); int b = n.num.size(); int d = a > b ? b : a; int c = 0; for (int i=0; i<d; ++i) { short v = num[i] + n.num[i] + c; tmp.num.push_back(v%10); c = v/10; } if (a > b) { for (int i=d; i<a; ++i) { short v = num[i] + c; tmp.num.push_back(v%10); c = v/10; } } else { for (int i=d; i<b; ++i) { short v = n.num[i] + c; tmp.num.push_back(v%10); c = v/10; } } return tmp; } bool operator < (const bign &n) const { if (num.size() != n.num.size()) { return num.size() < n.num.size(); } for (int i=num.size()-1; i>=0; --i) { if (num[i] != n.num[i]) { return num[i] < n.num[i]; } } return false; } friend istream &operator >> (istream &in, bign &n) { string s; in >> s; n = s.c_str(); return in; } friend ostream &operator << (ostream &out, const bign &n) { for (int i=n.num.size()-1; i>=0; --i) { out << n.num[i]; } return out; } }; int main() { bign n = "123"; bign m; m = "1123"; cout << n+m << endl; cout << (n<m) << endl; return 0; }