大整数类
C语言的时候,有很多整数溢出的情形。如果运算结果过大的话,就需要使用所谓的高精度算法,即用数组来储存整数,并模拟手算的方法进行四则运算。这些算法不难实现,但应考虑一个易用性问题----如果能像使用int一样方便使用大整数,将再好不过,至此,应该想到的就是使用struct。
1.1 大整数类BigInteger
结构体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.lenth()-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);
s.push_bach(x);
}
return *this;
}
};
***说明:***其中,s用来保存大整数的各个数位。例如,若是要表示1234,则s={4,3,2,1}.用vector而非数组保存数字的好处显而易见:不用关心这个整数到底有多大,vector会自动根据情况申请和释放内存。
上面的代码中还有赋值运算符,有了它就可以用x=123456789或者x="123456898765432123456789"这样的方式给x赋值了。