大整数类

大整数类又叫高精度。 就是求大数的四则运算的算法, (其实就是模拟小学生算数的方法, 什么? 你不会, 那你还不如小学生, 哈哈!)。 在这里只贴加法运算符的重载,其他的运算符与加法类似。闲言少叙, 直接上代码(小声告诉你, 里面用了几个库函数和STL, 嘿嘿!!!)。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<vector>
 4 #include<iostream>
 5 using namespace std;
 6 
 7 struct BigInteger {         // 定义大整数结构体 
 8   static const int BASE = 100000000; //8位8位的计算 
 9   static const int WIDTH = 8;
10   vector<int> s;                     //用来存8位8位的片段 
11 
12   BigInteger(long long num = 0) { *this = num; } // 构造函数 
13   BigInteger operator = (long long num) { // 赋值运算符。 
14     s.clear();
15     do {
16       s.push_back(num % BASE);
17       num /= BASE;
18     } while(num > 0);
19     return *this;
20   }
21   BigInteger operator = (const string& str) { //赋值运算符 
22     s.clear();
23     int x, len = (str.length() - 1) / WIDTH + 1;
24     for(int i = 0; i < len; i++) {
25       int end = str.length() - i*WIDTH;
26       int start = max(0, end - WIDTH);
27       sscanf(str.substr(start, end-start).c_str(), "%d", &x);//把字符串转化为8为的整数赋值给 x  
28       s.push_back(x);
29     }
30     return *this;
31   }
32   BigInteger operator + (const BigInteger& b) const {        //计算加法。g表示进位。 
33     BigInteger c;
34     c.s.clear();
35     for(int i = 0, g = 0; ; i++) {
36       if(g == 0 && i >= s.size() && i >= b.s.size()) break;
37       int x = g;
38       if(i < s.size()) x += s[i];
39       if(i < b.s.size()) x += b.s[i];
40       c.s.push_back(x % BASE);
41       g = x / BASE;
42     }
43     return c;
44   }
45 };
46 
47 ostream& operator << (ostream &out, const BigInteger& x) {
48   out << x.s.back();
49   for(int i = x.s.size()-2; i >= 0; i--) {
50     char buf[20];
51     sprintf(buf, "%08d", x.s[i]);
52     for(int j = 0; j < strlen(buf); j++) out << buf[j];
53   }
54   return out;
55 }
56 
57 istream& operator >> (istream &in, BigInteger& x) {
58   string s;
59   if(!(in >> s)) return in;
60   x = s;
61   return in;
62 }
63 
64 #include<set>
65 #include<map>
66 set<BigInteger> s;
67 map<BigInteger, int> m;
68 
69 int main() {
70   BigInteger y;
71   BigInteger x = y;
72   BigInteger z = 123;
73 
74   BigInteger a, b;
75   cin >> a >> b;
76   cout << a + b << "\n";
77   cout << BigInteger::BASE << "\n";
78   return 0;
79 }
View Code

 

posted @ 2015-05-16 21:43  草滩小恪  阅读(205)  评论(0编辑  收藏  举报