算法竞赛入门经典--大整数类
生活随笔
收集整理的這篇文章主要介紹了
算法竞赛入门经典--大整数类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
算法競賽入門經典BigInteger的實現,其中有些地方還是不是很懂,先存著,看懂的網友可以幫忙標注下,然后交流學習下。
參考代碼
struct BigInteger {static const int BASE = 100000000;//其數量級代表數組每個元素能夠存的位數。數量級是幾說明每個元素能存的位數就是幾。如10:則只能存0-9;100:存0-99 // static const int BASE = 100;static const int WIDTH = 8; // 代表數組每個元素能夠存的位數vector<int> s;BigInteger(long long num = 0) {*this = num; // 構造函數 用this指代大整數,對于指針來說永遠是4字節。很方便。 }BigInteger operator = (long long num) { // 賦值運算符s.clear();//cout<<num<<endl;do {cout<<num % BASE<<endl;s.push_back(num % BASE);//老套路了,先求余,再把余舍去。進制轉換也是這個原理(只不過最后是倒著輸出) num /= BASE;cout<<num<<endl;} while(num > 0);return *this;}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) const {//大佬寫的很棒,但我不懂。 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;} };ostream& operator << (ostream &out, const BigInteger& x) {//重載 << out << x.s.back();//第一部分有可能不會占滿,所以直接輸出。 for(int i = x.s.size()-2; i >= 0; i--) {//逆序輸出 數組 char buf[20];//用于存放數據 sprintf(buf, "%08d", x.s[i]);// 將 每個元素 放到 buf字符串中去,不足的左補0 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;//先把字符串讀進 s x = s;// 把 s 賦值給 要賦的那個值。 x是那個值的引用哦。 return in; }#include<set> #include<map> set<BigInteger> s; map<BigInteger, int> m;int main() {BigInteger y;BigInteger x = y;BigInteger z = 123;BigInteger a, b;cin >> a >> b;cout << a + b << "\n";cout << BigInteger::BASE << "\n";//BigInteger b(10),a; // a = b; // BigInteger b; // b ="1234567890456789123";//cout<<b;return 0; }總結
以上是生活随笔為你收集整理的算法竞赛入门经典--大整数类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 执行Hive的查询语句报错:java.l
- 下一篇: 【解决】如何打开.ipynb文件