#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<sstream>
#include<ostream>
#include<string.h>
using namespace std;
class BigInteger {
public:
static const int Base = 100000000;
static const int Width = 8;
vector <int> number;
BigInteger(long long num = 0) {
*this = num;
}
BigInteger operator = (long long num) {
number.clear();
do {
number.push_back(num % Base);
num /= Base;
} while (num > 0);
return *this;
}
BigInteger operator =(const string& s) {
number.clear();
int len = (s.length() - 1) / Width + 1;
int end, start;
int n;
for (int i = 0; i < len; i++) {
end = s.length() - i*Width;
if(end-Width<0)//不能用s.length() - i*Width-1代替end,不然就会throw出错,strat的值就是不定的值(不知道为什么)
start=0;
else
start=end-Width;
sscanf(s.substr(start,end-start).c_str(), "%d", &n);
number.push_back(n);
}
return *this;
}
BigInteger operator + (const BigInteger& b) const {
BigInteger c;
c.number.clear();
for(int i = 0, g = 0; ; i++) {
if(g == 0 && i >= number.size() && i >= b.number.size())
break;
int x = g;
if(i < number.size()) x += number[i];
if(i < b.number.size()) x += b. number[i];
c.number.push_back(x % Base);
g = x / Base;
}
return c;
}
};
ostream& operator<<(ostream &out, const BigInteger& x) {
out << x.number.back();
for (int i = x.number.size() - 2; i >= 0; i--) {
char buf[20];
sprintf(buf, "%08d", x.number[i]);
for (int j = 0; j < strlen(buf); j++)
out << buf[j];
}
return out;
}
istream& operator >> (istream &in, BigInteger& x) {
string s;
if(!(in >> s))
return in;
x = s;
return in;
}
int main() {
BigInteger i(3140103139),j(0);
cout<<i<<endl;//3140103139
cin>>i; //8888888888888888888888888888888888888888888888888888888888888888888888888888888888888
j="9999999999999999999999999999999999999999999999999999999999999999999999999999999999";
cout<<i+j<<endl;//8898888888888888888888888888888888888888888888888888888888888888888888888888888888887
cout<<j;//9999999999999999999999999999999999999999999999999999999999999999999999999999999999
}
大整数类源码
最新推荐文章于 2023-12-02 11:18:35 发布