c++高精度重载运算符写法
作者:
syf666
,
2021-10-22 11:24:47
,
所有人可见
,
阅读 336
#include <bits/stdc++.h>
using namespace std;
struct HP {
vector<int> a;
HP(string x = "empty") {
if (x == "empty") return;
for (int i = x.size() - 1; i >= 0; -- i)
a.push_back(x[i] - '0');
}
HP operator+ (const HP &x) const {
HP c = HP("");
int t = 0;
for (int i = 0; i < a.size() || i < x.a.size(); ++ i) {
if (i < a.size()) t += a[i];
if (i < x.a.size()) t += x.a[i];
c.a.push_back(t % 10);
t /= 10;
}
if (t) c.a.push_back(1);
return c;
}
bool operator< (const HP &x) const {
if (a.size() != x.a.size())
return a.size() < x.a.size();
for (int i = a.size() - 1; ~i; -- i)
if (a[i] != x.a[i])
return a[i] < x.a[i];
return false;
}
HP operator- (const HP &x) const {
HP c = HP("");
int t = 0;
for (int i = 0; i < a.size(); ++ i){
t = a[i] - t;
if (i < x.a.size()) t -= x.a[i];
c.a.push_back((t + 10) % 10);
if (t < 0) t = 1;
else t = 0;
}
while (c.a.size() > 1 && c.a.back() == 0) c.a.pop_back();
return c;
}
HP operator* (const HP &x) const {
HP c = HP("");
c.a.resize(a.size() + x.a.size());
for (int i = 0; i < a.size(); ++ i) {
int t = 0;
for (int j = 0; j < x.a.size(); ++ j) {
c.a[i + j] += t + a[i] * x.a[j];
t = c.a[i + j] / 10;
c.a[i + j] %= 10;
}
c.a[i + x.a.size()] = t;
}
while (c.a.size() > 1 && c.a.back() == 0) c.a.pop_back();
return c;
}
pair<HP, int> operator/ (const int &b) const { // LP
HP c = HP("");
int r = 0;
for (int i = a.size() - 1 ; ~i; -- i){
r = r * 10 + a[i];
c.a.push_back(r / b);
r %= b;
}
reverse(c.a.begin(), c.a.end());
while(c.a.size() > 1 && c.a.back()==0) c.a.pop_back();
return {c, r};
}
void out() {
for (int i = a.size() - 1; i >= 0; -- i) printf("%d", a[i]);
}
};
int main() {
}