【算法重修】高精度算法(压位+STL)

开新坑了,激动ing٩(๑>◡<๑)۶……

算法思想

高精度的关键在于模拟,即模拟我们的竖式运算形式:

大整数类(Bigint)设计

  • 压位存储,Bit(位)和Base(基数,即10^Bit)
  • 用STL中的vector,且封装为private
  • 由于可能为负,需设置sgn(符号)表示-1、1

运算符重载

  • 需要注意流提取运算符>>和流插入运算符<<是在头文件iostream中重载的,我们不能将其设为私有(private)(除非在头文件里改 ),所以只能将其设为友元函数(friend)重载
  • 返回值必须为引用,&istream&ostream

代码实现

构造函数&等号

class Bigint{
	private:
		static const int Bit=8;
		static const int Base=1e8;
		vector<int> v;
		int sgn=1;
	public:
	    Bigint(long long n=0){
	    	*this=n;
		}
	    Bigint operator =(long long n){
	        v.clear();
	        while(n){
	            v.push_back(n%Base);
	            n/=Base;
	        }
	        return *this;
	    }
	    Bigint operator =(const string& s){
	        v.clear();
	        int len=(s.size()-1)/Bit+1;
	        For(i,0,len){
	            int r=s.size()-i*Bit;
	            int l=max(0,r-Bit);
	            int x=atoi(s.substr(l,r-l).c_str());
	            v.push_back(x);
	        }
	        return *this;
	    }

输入输出

同样在类内定义

friend ostream& operator <<(ostream& out, const Bigint& n){
	    	out<<n.v.back();
	    	for(int i=n.v.size()-2; i>=0; i--)
	    		out<<setw(Bit)<<setfill('0')<<n.v[i];
	    	return out;
		}
		friend istream& operator >>(istream& in, Bigint& n){
			string s;
			if (in>>s)
				n=s;
			return in;
		}

加法

Bigint operator +(Bigint &n){
	    	Bigint ans;
	        ans.v.clear();
	        for(int i=0, g=0; ; i++){
	            if (g==0 && i>=v.size() && i>=n.v.size())
					break;
	            int x=g;
	            if (i<v.size())
					x+=v[i];
	            if (i<n.v.size())
					x+=n.v[i];
	            ans.v.push_back(x%Base);
	            g=x/Base;
	        }
	        return ans;
	    }

其他还有待完善,占个坑先~ ⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值