c++实现superint类
时间: 2023-10-28 09:04:32 浏览: 49
下面是一个简单的超大整数(SuperInt)类的 C++ 实现,支持基本的算术运算和比较运算:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class SuperInt {
private:
static const int MAX_LEN = 1000; // 数组最大长度
int num[MAX_LEN]; // 数组存储超大整数
bool positive; // 是否为正数
public:
// 构造函数
SuperInt() {
memset(num, 0, sizeof(num)); // 初始化为 0
positive = true; // 默认为正数
}
SuperInt(const char *s) {
memset(num, 0, sizeof(num)); // 初始化为 0
int len = strlen(s);
positive = true; // 默认为正数
if (s[0] == '-') {
positive = false;
len--;
s++;
}
for (int i = 0; i < len; i++) {
num[i] = s[len - 1 - i] - '0'; // 逆序存储
}
}
// 输出运算符重载
friend ostream& operator<<(ostream &out, const SuperInt &a) {
if (!a.positive) {
out << '-';
}
int i = MAX_LEN - 1;
while (i >= 0 && a.num[i] == 0) {
i--;
}
if (i < 0) {
out << '0';
} else {
for (; i >= 0; i--) {
out << a.num[i];
}
}
return out;
}
// 加法运算符重载
friend SuperInt operator+(const SuperInt &a, const SuperInt &b) {
SuperInt c;
if (a.positive == b.positive) { // 同号相加
c.positive = a.positive;
int carry = 0;
for (int i = 0; i < MAX_LEN; i++) {
c.num[i] = a.num[i] + b.num[i] + carry;
carry = c.num[i] / 10;
c.num[i] %= 10;
}
} else { // 异号相减
c = a - (-b);
}
return c;
}
// 减法运算符重载
friend SuperInt operator-(const SuperInt &a, const SuperInt &b) {
SuperInt c;
if (a.positive == b.positive) { // 同号相减
if (a >= b) {
c.positive = a.positive;
int borrow = 0;
for (int i = 0; i < MAX_LEN; i++) {
c.num[i] = a.num[i] - b.num[i] - borrow;
if (c.num[i] < 0) {
borrow = 1;
c.num[i] += 10;
} else {
borrow = 0;
}
}
} else {
c = b - a;
c.positive = !a.positive;
}
} else { // 异号相加
c = a + (-b);
}
return c;
}
// 负号运算符重载
SuperInt operator-() const {
SuperInt a = *this;
a.positive = !positive;
return a;
}
// 大于等于运算符重载
friend bool operator>=(const SuperInt &a, const SuperInt &b) {
if (a.positive != b.positive) {
return a.positive;
} else {
for (int i = MAX_LEN - 1; i >= 0; i--) {
if (a.num[i] != b.num[i]) {
return (a.positive ? a.num[i] > b.num[i] : a.num[i] < b.num[i]);
}
}
return true;
}
}
// 小于运算符重载
friend bool operator<(const SuperInt &a, const SuperInt &b) {
return !(a >= b);
}
// 大于运算符重载
friend bool operator>(const SuperInt &a, const SuperInt &b) {
return b < a;
}
// 小于等于运算符重载
friend bool operator<=(const SuperInt &a, const SuperInt &b) {
return !(b < a);
}
};
int main() {
SuperInt a = "123456789";
SuperInt b = "-987654321";
cout << a << endl;
cout << b << endl;
cout << a + b << endl;
cout << a - b << endl;
return 0;
}
```