C++应用之自定义大整数类

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43269048/article/details/99865739

写在前面:C语言在应用时有很多整数溢出的情形,如果运算结果很大,就需要用到所谓的高精度算法,即用数组来储存整数,并模拟手算的方法进行四则运算,这些算法并不难实现,但是考虑到易用性问题,即如果能像使用int一样方便地使用大整数,在这里我们采取struct来构造大整数类。
结构体BigInteger可用于储存高精度非负整数。

struct BigInteger{
	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/=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);
			scanf(str.substr(start,end-start).c_str(),"%d",&x);//将长字符串分为几段来保存,每段的长度由end-start来决定
			s.push_back(x);
		} 
		return *this;
	}
}; 

其中,s用来保存大整数的各个数位。例如,若是要表示1234,第一种方式 x=1234,则s={4,3,2,1},若是第二种方式 x=“12345678912”,即字符串赋值,则s={45678912,123}。用vector而非数组保存数字我们不需要关心这个整数到底有多大,vector会自动根据情况申请和释放内存。

猜你喜欢

转载自blog.csdn.net/qq_43269048/article/details/99865739