大整数类(C++ 简化版 不含负数 不含乘法除法)

版权声明:原创文章转载时请注明出处 https://blog.csdn.net/weixin_42856843/article/details/89358558

大整数类(C++ 简化版 不含负数 不含乘法除法)

/*
	简化版
	不含负数
	不含乘法除法
*/
#include <bits/stdc++.h>
#define ll long long
#define _for(i, a) for(int i = 0; i < (a); i++)
#define _rep(i ,a, b) for(int i = (a); i <= (b); i++)
using namespace std;
struct BIGNUM {
	static const int BASE = 100000000;
	static const int WIDTH = 8;
	vector<int> s;

	BIGNUM(ll num = 0) { *this = num; }
	BIGNUM operator = (ll num) {
		s.clear();
		while (num > 0) {
			s.push_back(num % BASE);
			num /= BASE;
		}
		return *this;
	}

	BIGNUM operator = (const string& str) {
		s.clear();
		int x, len = (str.length() - 1) / WIDTH + 1;
		_for(i, len) {
			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;
	}//赋值运算

	BIGNUM operator + (const BIGNUM& b) const {
		BIGNUM 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];
			g = x / BASE;
			c.s.push_back(x);
		}
		return c;
	}//加法运算

	BIGNUM operator - (const BIGNUM& b) const {
		BIGNUM c;
		c.s.clear();
		int x, g = 0, i = 0;
		do {
			x = s[i] - g;
			if (i < b.s.size()) x -= b.s[i];
			if (x < 0) {
				x += BASE;
				g = 1;
			}
			else g = 0;
			c.s.push_back(x);
			i++;
		} while (i < s.size());
		return c;
	}//减法运算 默认大减小 且都大于0

	bool operator < (const BIGNUM& b) const {
		if (s.size() != b.s.size()) return s.size() < b.s.size();
		for (int i = s.size() - 1; i >= 0; i--) {
			if (s[i] != b.s[i]) return s[i] < b.s[i];
		}
		return false;//相等
	}//重载小于号

	//其他比较运算
	bool operator > (const BIGNUM& b) const { return b < *this; }
	bool operator <= (const BIGNUM& b) const { return !(b < *this); }
	bool operator >= (const BIGNUM& b) const { return !(*this < b); }
	bool operator != (const BIGNUM& b) const { return b < *this || *this < b; }
	bool operator == (const BIGNUM& b) const { return !(b < *this || *this < b); }
};
ostream& operator << (ostream &out, const BIGNUM& x) {
	out << x.s.back();
	for (int i = x.s.size() - 2; i >= 0; i--) {
		char buf[10];
		sprintf(buf, "%08d", x.s[i]);
		_for(j, strlen(buf)) out << buf[j];
	}
	return out;
}//重载输出运算符

istream& operator >> (istream &in, BIGNUM &x) {
	string s;
	if (!(in >> s)) return in;
	x = s;
	return in;
}//重载输入运算符

int main() {
	BIGNUM a, b;
	a = "10000000000";
	b = 100;
	cout << a - b;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42856843/article/details/89358558