c++大整数类的几种实现方法与解析

在oj上做题时,相信大家遇到过很多要求大整数的题目,这时候,我们就需要用到所谓的高精度算法,即用数组来储存整数,模拟四则运算以及其他常见的运算,下面就让我们来分析一下几种实现大整数的方法


一.用vector来储存大整数

<span style="font-size:24px;color:#FF0000;"><strong><span style="font-size:14px;color:#000000;">#include<iostream>
#include<vector>
#include<stack>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
class BigInteger  
{
public:
	static const int base=100000000;
	static const int width=8;
	vector<int>s;
	BigInteger(long long num=0){*this=num;}    //构造函数
	BigInteger operator=(long long num)
	{
		s.clear();
		do{
			s.push_back(num%base);
			num=num/base;
		}while(num>0);
		return *this;
	}
	BigInteger operator=(const string &str)      //重载=号
	{
		s.clear();
		int x,len=(str.length()-1)/width+1;
		for(int i=0;i<len;i++){
			int end=str.length()-i*width;
			int start=max(0,end-width);
			sscanf(str.substr(start,end-start).c_str(),"%d",&x);    //格式符%d是读入十进制整数
			                                                    //string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址
			s.push_back(x);
		}
		return *this;
	}
	friend ostream & operator<<(ostream &out,const BigInteger& x)   //重载输出号
	{
	out<<x.s.back();
	for(int i=x.s.size()-2;i>=0;i--){
		char buf[20];
		sprintf(buf,"%08d",x.s[i]);
		for(int j=0;j<int(strlen(buf));j++)
			out<<buf[j];
	}
	return out;
	}
	friend istream & operator>>(istream &in,BigInteger& x)   //重载输入号
	{
	string s;
	if(!(in>>s)) return in;
	x=s;
	return in;
	}
	BigInteger operator+(const BigInteger& b)const   //重载加号
	{
		BigInteger 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];
			c.s.push_back(x%base);
			g=x/base;
		}
		return c;
	}
	BigInteger operator-(const BigInteger& b)   //重载减号,默认前面大于后面
	{
		BigInteger c;
		c.s.clear();
		if(*this>b){
			int i,g;
		for(i=0,g=0;;i++){
			if(g==0&&i>=b.s.size()) break;
			int x=g;
			if(s[i]<b.s[i]){
				s[i+1]-=1;
				s[i]=s[i]+base;
			}
			if(i<s.size()) x+=s[i];
			if(i<b.s.size()) x-=b.s[i];
			c.s.push_back(x%base);
			g=x/base;
		}
		int x=0;
		for(;i<s.size();i++){
			x+=s[i];
			c.s.push_back(x%base);
			x=x/base;
		}
		}
		return c;
	}
	bool operator<(const BigInteger& b)const   //重载小于号
	{
		if(s.size()!=b.s.size()) return s.size()<b.s.size();
		for(int i=s.siz
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值