大整数类
本来紫书上有,但是跟这个又不太一样
新学了 字符串反转的操作
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstring>
#include <algorithm>
using namespace std;
class Decimal
{
private:
string s;
int len;
public:
Decimal(int a) {
string str;
stringstream st;
st << a;
st >> str;
s = str;
len = str.length();
}
Decimal(string ss = "") {
s = ss;
len = s.length();
}
friend istream &operator>> (istream &in, Decimal &b) {
in >> b.s;
b.len = b.s.length();
return in;
}
friend ostream &operator<< (ostream &out, Decimal &b) {
//cout << "+++++++++++++" <<endl;
out << b.s;
return out;
}
string operator +(Decimal b) {
string c;
if(len < b.len) {
string tmp = s;
s = b.s;
b.s = tmp;
}
int lent = len - b.len;
len = max(len, b.len);
string ss(lent , '0');
b = ss + b.s;
int t = 0;
for(int i = len-1; i >= 0; i--) {
int sum = (s[i]-'0') + (b.s[i]-'0') + t;
c.push_back((sum%10) + '0');
t = sum / 10;
}
if(t == 1)
c.push_back('1');
string s_(c.rbegin(), c.rend());
//cout << "++++++++++++++++" << endl;
return s_;
}
string operator +(int b) {
string str;
stringstream st;
st << b;
st >> str;
string c;
if(len < str.length()) {
string tmp = s;
s = str;
str = tmp;
}
int lent = len - str.length();
len = s.length();
string ss(lent ,'0');
str = ss + str;
int t = 0;
for(int i = len - 1; i >= 0; i--) {
int sum = (s[i] - '0') + (str[i] - '0') + t;
c.push_back((sum%10) + '0');
t = sum / 10;
}
if(t == 1)
c.push_back('1');
string s_(c.rbegin(), c.rend());
return s_;
}
Decimal &operator++() {
int sum;
string c;
int t = 0;
for(int i = len - 1; i >= 0; i--) {
if(i == len - 1) {
sum = (s[i]-'0') + 1;
}
else
sum = s[i] - '0' + t;
c.push_back((sum%10) + '0');
t = sum / 10;
}
if(t == 1)
c.push_back('1');
string ss(c.rbegin(), c.rend());
s = ss;
return *this;
}
int getLength() {
return len;
}
char operator [] (int i) {
return s[i];
}
};
int main()
{
Decimal a, b, c, d, e, f("554433"), g(12345);
int i;
cin>>a>>b>>i;
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"i = "<<i<<endl;
c = a + b;
d = ++a;
e = b + i;
cout<<"a = "<<a<<endl;
cout<<"c = "<<c<<endl;
cout<<"d = "<<d<<endl;
cout<<"e = "<<e<<endl;
cout<<"f = "<<f<<endl;
cout<<"g = "<<g<<endl;
cout<<c[0];
for (i = 1; i < c.getLength(); i++)
{
cout<<" "<<c[i];
}
cout<<endl;
return 0;
}