标签:tmp const 高精度 int BigInt result 模板 size
#include <cstring>
#include <iostream>
#include <vector>
struct BigInt {
std::vector<char> v;
BigInt() {
*this = 0;
}
BigInt(int x) {
*this = x;
}
BigInt &operator=(int x) {
v.clear();
do v.push_back(x % 10); while (x /= 10);
return *this;
}
BigInt &operator=(const BigInt &x) {
v.resize(x.v.size());
memcpy(const_cast<char *>(v.data()), x.v.data(),
x.v.size() * sizeof(char));
return *this;
}
};
std::ostream &operator<<(std::ostream &out, const BigInt &x) {
for (int i = x.v.size() - 1; i >= 0; i--) out << (char)(x.v[i]
+ '0');
return out;
}
BigInt operator+(const BigInt &a, const BigInt &b) {
BigInt result;
result.v.clear();
bool flag = false;
for (int i = 0; i < (int)std::max(a.v.size(), b.v.size());
i++) {
int tmp = 0;
if (i < (int)a.v.size()) tmp += a.v[i];
if (i < (int)b.v.size()) tmp += b.v[i];
if (flag) tmp++, flag = false;
if (tmp >= 10) tmp -= 10, flag = true;
result.v.push_back(tmp);
}
if (flag) result.v.push_back(1);
return result;
}
BigInt &operator+=(BigInt &a, const BigInt &b) {
return a = a + b;
}
BigInt operator-(const BigInt &a, const BigInt &b) {
BigInt result;
result.v.clear();
bool flag = false;
for (int i = 0; i < (int)a.v.size(); i++) {
int tmp = a.v[i];
if (i < (int)b.v.size()) tmp -= b.v[i];
if (flag) tmp--, flag = false;
if (tmp < 0) tmp += 10, flag = true;
result.v.push_back(tmp);
}
int size = result.v.size();
while (size > 1 && result.v[size - 1] == 0) size--;
result.v.resize(size);
return result;
}
BigInt operator*(const BigInt &a, const BigInt &b) {
BigInt result;
result.v.resize(a.v.size() + b.v.size());
for (int i = 0; i < (int)a.v.size(); i++) {
for (int j = 0; j < (int)b.v.size(); j++){
result.v[i + j] += a.v[i] * b.v[j];
result.v[i + j + 1] += result.v[i + j] / 10;
result.v[i + j] %= 10;
}
}
int size = result.v.size();
while (size > 1 && result.v[size - 1] == 0) size--;
result.v.resize(size);
return result;
}
转自 Menci 的博客 : https://oi.men.ci/bigint-template/
标签:tmp,const,高精度,int,BigInt,result,模板,size 来源: https://www.cnblogs.com/dhclient/p/16438847.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。