大整数类BigInteger(存储高精度非负整数)

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct BigInteger { //存储高精度非负整数
	static const int BASE = 100000000; //静态成员变量,在外部用BigInteger::BASE调用
	static const int WIDTH = 8;
	vector<int> v;
	BigInteger(long long num = 0) { *this = num; }
	BigInteger(const string& s=NULL) { *this = s; }
	BigInteger operator =(long long num) {
		v.clear();
		do {
			v.push_back(num % BASE);//每次取前八位
			num /= BASE;
		} while (num > 0);
		return *this;
	}
	BigInteger operator=(const string& s) {
		v.clear();
		int x, len = (s.length() - 1) / WIDTH + 1;
		for (int i = 0; i < len; i++) {
			int end = s.length() - i * WIDTH;
			int start = max(0, end - WIDTH);
			sscanf(s.substr(start, end - start).c_str(), "%d", &x);
			v.push_back(x);
		}
		return *this;
	}
	BigInteger operator +(const BigInteger& x) {
		BigInteger c(0);
		c.v.clear();
		for (int i = 0, g = 0;; i++) { // g表示低位进位数,i取每一个位
			if (g == 0 && i >= v.size() && i >= x.v.size()) { break; }
			int num = g;
			if (i < v.size()) num += v[i];
			if (i < x.v.size()) num += x.v[i];
			c.v.push_back(num % BASE);
			g = num / BASE;
		}
		return c;
	}
	BigInteger operator +=(const BigInteger& x) {
		*this = *this + x;
		return *this;
	}
	bool operator <(const BigInteger& x) const {
		if (v.size() != x.v.size()) return v.size() < x.v.size();
		for (int i = v.size() - 1; i >= 0; i++) {
			if (v[i] != x.v[i]) return v[i] < x.v[i];
		}
		return false;//相等
	}
	bool operator <=(const BigInteger& x) const{ return !(x < *this);}
	//同理可定义 > >= != ==符号
};
ostream& operator<<(ostream& out, const BigInteger& x) {
	out << x.v.back();
	for (int i = x.v.size() - 2; i >= 0; i--) {
		char buf[20];
		sprintf(buf, "%08d", x.v[i]);
		for (int j = 0; j < strlen(buf); j++) { cout << buf[j]; }
	}
	return out;
}
istream& operator>>(istream& in, BigInteger& x) {
	string s;
	if(!(cin>>s)) return in;
	x = s;
	return in;
}
int main()
{
	string s = "123456789000000000567890";
	struct BigInteger big(s);
	for (int i = 0; i < big.v.size(); i++) {
		cout << big.v[i] << endl;
	}
	cout << big << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值