大整数类源码

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<sstream>
#include<ostream>
#include<string.h> 
using namespace std;
class BigInteger {
public:
	static const int Base = 100000000;
	static const int Width = 8;
	vector <int> number;

	BigInteger(long long num = 0) {
		*this = num;
	}

	BigInteger operator = (long long num) {
		number.clear();
		do {
			number.push_back(num % Base);
			num /= Base;
		} while (num > 0);
		return *this;
	}
	BigInteger operator =(const string& s) {
		number.clear();
		int  len = (s.length() - 1) / Width + 1;
		int end, start;
		int n;
		for (int i = 0; i < len; i++) {
			end = s.length() - i*Width;
			 if(end-Width<0)//不能用s.length() - i*Width-1代替end,不然就会throw出错,strat的值就是不定的值(不知道为什么) 
			 start=0;
			 else
			 start=end-Width;
			sscanf(s.substr(start,end-start).c_str(), "%d", &n);
			number.push_back(n);
		}
		return *this;
	}
	BigInteger operator + (const BigInteger& b) const {
  		BigInteger c;
    	c.number.clear();
		for(int i = 0, g = 0; ; i++) {
	    	if(g == 0 && i >= number.size() && i >= b.number.size())
		  	 break;
		int x = g; 
		if(i < number.size()) x += number[i];
			if(i < b.number.size()) x += b. number[i];
				c.number.push_back(x % Base);
				g = x / Base;
		}
		return c; 
	}

};
ostream& operator<<(ostream &out, const BigInteger& x) {
	out << x.number.back();
	for (int i = x.number.size() - 2; i >= 0; i--) {
		char buf[20];
		sprintf(buf, "%08d", x.number[i]);
		for (int j = 0; j < strlen(buf); j++)
			out << buf[j];
	}
	return out;
}
istream& operator >> (istream &in, BigInteger& x) {
  	string s;
    if(!(in >> s))
		return in;
	x = s;
	return in; 
}

int main() {
	BigInteger i(3140103139),j(0);
	cout<<i<<endl;//3140103139
	cin>>i; //8888888888888888888888888888888888888888888888888888888888888888888888888888888888888 
	j="9999999999999999999999999999999999999999999999999999999999999999999999999999999999";
	cout<<i+j<<endl;//8898888888888888888888888888888888888888888888888888888888888888888888888888888888887 
	cout<<j;//9999999999999999999999999999999999999999999999999999999999999999999999999999999999
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值