高精度计算
加
string add(string a,string b){
if(a.size() > b.size()) swap(a,b);
b.insert(b.begin(),'0');
int t = 0;
for(int i = b.size()-1,j = a.size()-1;i>=0;i--,j--){
int cur;
if(j>=0) cur = (a[j]-'0') + (b[i]-'0') + t;
else cur = (b[i] - '0') +t;
b[i] = (cur%10) + '0';
t = cur/10;
}
int idx = b.find_first_not_of('0');
return idx != -1? b.substr(idx): "0";
}
减
string sub(string a,string b){
//a大b小
int t = 0;
for(int i = a.size()-1,j = b.size()-1;i>=0;i--,j--){
int up = 0,down = 0;
up = (a[i]-'0') + t; t = 0;
if(j>=0) down = (b[j]-'0');
if(up < down) up+=10,t = -1;
int cur = up-down;
a[i] = cur+'0';
}
int idx = a.find_first_not_of('0');
return idx != -1? a.substr(idx) : "0";
}
乘(高精度*低精度)
string mul(string a,ll b){
string c = "";
ll t = 0;
for(int i = a.size()-1;i>=0 || t;i--){
if(i>=0) t += (a[i]-'0')*b;
c += (t%10) +'0';
t/=10;
}
reverse(c.begin(),c.end());
return c;
}
除(高精度/低精度)
返回商的整数部分
string div(string a,ll b){
string c = "";
ll cur = 0;
for(int i = 0;i<a.size();i++){
cur = cur*10 + (a[i]-'0');
c += to_string(cur/b);
cur %= b;
}
int idx = c.find_first_not_of('0');
return idx!=-1 ? c.substr(idx) : "0";
}
比较大小
bool cmp(string a,string b){
int idx1 = a.find_first_not_of('0'),idx2 = b.find_first_not_of('0');
a = idx1!=-1? a.substr(idx1) : "0";
b = idx2!=-1? b.substr(idx2) : "0";
if(a.size() != b.size()) return a.size() >= b.size();
return a>=b;
}
175

被折叠的 条评论
为什么被折叠?



