开新坑了,激动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;
}
其他还有待完善,占个坑先~ ⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄