大數據操作,有如下問題:
計算:456789135612326542132123+14875231656511323132
??456789135612326542132123*14875231656511323132
比較:7531479535511335666686565>753147953551451213356666865 ?
long long類型存儲不了,存儲不了就實現不成計算,怎么辦???
為了解決以上問題,所以得定義一種結構類型以存儲這些數據,并重載運算符支持這些數據的操作,為了方便代碼的復用因此有了如下代碼:
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;const int maxn = 200;
struct bign{int len, s[maxn];/*以下的構造函數是C++中特有的,作用是進行初始化。事實上,當定義bign x時,就會執行這個函數,把x.s清零,并賦x.len=1 。需要說明的是,在C++中,并不需要typedef就可以直接用結構體名來定義,而且還提供“自動初始化”的功能,從這個意義上說,C++比C語言方便 */ bign() {memset(s, 0, sizeof(s));len = 1;}bign(int num) {*this = num;}//定義為const參數,作用是 不能對const參數的值做修改 bign(const char* num) {*this = num;}/*以上是構造方法,初始化時對執行相應的方法*/bign operator = (int num) {char s[maxn];sprintf(s, "%d", num);*this = s;return *this;} //函數定義后的const關鍵字,它表明“x.str()不會改變x” string str() const {string res = "";for(int i = 0; i < len; i++) res = (char)(s[i] + '0') + res;if(res == "") res = "0";return res;}void clean() {while(len > 1 && !s[len-1]) len--;}/* 以下是重載操作符 */ bign operator = (const char* num) {//逆序存儲,方便計算 len = strlen(num);for(int i = 0; i < len; i++) s[i] = num[len-i-1] - '0';return *this;}bign operator + (const bign& b) const{bign c;c.len = 0;for(int i = 0, g = 0; g || i < max(len, b.len); i++) {int x = g;if(i < len) x += s[i];if(i < b.len) x += b.s[i];c.s[c.len++] = x % 10;g = x / 10;}return c;}bign operator * (const bign& b) {bign c; c.len = len + b.len;for(int i = 0; i < len; i++)for(int j = 0; j < b.len; j++)c.s[i+j] += s[i] * b.s[j];for(int i = 0; i < c.len-1; i++){c.s[i+1] += c.s[i] / 10;c.s[i] %= 10;}c.clean();return c;}bign operator - (const bign& b) {bign c; c.len = 0;for(int i = 0, g = 0; i < len; i++) {int x = s[i] - g;if(i < b.len) x -= b.s[i];if(x >= 0) g = 0;else {g = 1;x += 10;}c.s[c.len++] = x;}c.clean();return c;}bool operator < (const bign& b) const{if(len != b.len) return len < b.len;for(int i = len-1; i >= 0; i--)if(s[i] != b.s[i]) return s[i] < b.s[i];return false;}bool operator > (const bign& b) const{return b < *this;}bool operator <= (const bign& b) {return !(b > *this);}bool operator == (const bign& b) {return !(b < *this) && !(*this < b);}bign operator += (const bign& b) {*this = *this + b;return *this;}
};istream& operator >> (istream &in, bign& x) {string s;in >> s;x = s.c_str();return in;
}ostream& operator << (ostream &out, const bign& x) {out << x.str();return out;
}int main() {bign a;cin >> a;a += "123456789123456789000000000";cout << a*2 << endl;return 0;
}