标签:tor char s memset pre bool string cpp his ems
高精度重载运算符模板
struct bign{
//存在性定义
int len, s[2010];
//初始化
bign () {memset(s, 0, sizeof(s)), len = 1;}
bign (int num){ *this = num;}
bign (char *num) {*this = num;}
bign (const char *num){ *this = num;}
//重载 =
bign operator = (int num) {
char s[2010];
sprintf(s, "%d", num);
*this = s;
return *this;
}
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 clear(){ 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 = *this;
int i = 0;
for (int i = 0; i < b.len; i++) {
c.s[i] += b.s[i];
if (c.s[i] > 9) c.s[i] %= 10, c.s[i + 1] ++;
}
while (c.s[i] > 9) c.s[i++] %= 10, c.s[i]++;
c.len = max(len, b.len);
if (c.s[i] && c.len <= i) c.len = i + 1;
return c;
}
bign operator - (const bign &b) const {
bign c = *this;
int i = 0;
for (int i = 0; i < b.len; ++i) {
c.s[i] -= b.s[i];
if (c.s[i] < 0) c.s[i] += 10, c.s[i + 1] --;
}
while (c.s[i] < 0) c.s[i++] += 10, c.s[i] --;
c.clear();
return c;
}
bign operator * (const bign &b) const {
int i, j;
bign c;
c.len = len + b.len;
for (int j = 0; j < b.len; j++)
for (int i = 0; i < len; i++)
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.clear();
return c;
}
bign operator / (const bign &b) const {
bign c = *this, a = 0;
int i, j;
for (i = len - 1; i >= 0; i --) {
a = a * 10 + s[i];
for (j = 0; j < 10; j++)
if (a < b * (j + 1)) break;
c.s[i] = j;
a = a - b * j;
}
c.clear();
return c;
}
bign operator % (const bign &b) const {
int i, j;
bign c = 0;
for (int i = len - 1; i >= 0; i--) {
c = c * 10 + s[i];
for (int i = len - 1; i >= 0; --i){
if (c < b * (j + 1)) break;
c = c - b * j;
}
}
return c;
}
bign operator += (const bign &b){
*this = *this + b;
return *this;
}
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) const {return !(b < *this);}
bool operator >= (const bign &b) const {return !(*this < b);}
bool operator == (const bign &b) const {return !(b < *this) && !(*this < b);}
bool operator != (const bign &b) const {return (b < *this) || (*this < b);}
};
//流输入输出重载
istream& operator >> (istream &in, bign &x) {
string s;
in >> s;
x = s.c_str();
return in;
}
ostream& operator << (ostream &out, bign &x){
out << x.str();
return out;
}
标签:tor char s memset pre bool string cpp his ems
原文地址:https://www.cnblogs.com/sun915/p/9501509.html