Problem A: 大整数的加法运算


Description


我们知道,C++中的整数类型,如short、int、long和long long等都有确定的表示范围,超大的整数是不能表示的。请定义一个类Decimal,用于表示大整数,并实现如下方法:

1.根据给出的main函数定义的构造函数。

2. 重载加法(“+”)运算符,可以实现一个Decimal对象与另一个Decimal对象求和、与一个int类型的数值求和。

3. 重载前缀自增运算符。

4. 重载下标运算符,用于求当前对象的指定下标位置的数字。

5. 重载输入、输出运算符。


Input


输入3个数,前2个可能会超出unsigned long long的表示范围,最后1个是一个int类型的非负整数。

不考虑负数。


Output


见样例。



#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

const int maxn = 10000 + 10;

class Decimal {
private:
int a[maxn], n;
public:
Decimal() { n = 0; }
Decimal(int x) {
n = 0;
while (x) {
a[n++] = x % 10;
x /= 10;
}
}
Decimal(string s) {
n = 0;
for (int i = s.size() - 1; i >= 0; i--) {
a[n++] = s[i] - '0';
}
}
Decimal operator + (const Decimal &d) {
Decimal ans;
int base = 0;
for (int i = 0; i < n && i < d.n; i++) {
int temp = a[i] + d.a[i] + base;
ans.a[i] = temp % 10;
if (temp > 9) base = 1;
else base = 0;
}
if (n < d.n) {
for (int i = n; i < d.n; i++) {
int temp = d.a[i] + base;
ans.a[i] = temp % 10;
if (temp > 9) base = 1;
else base = 0;
}
}
else {
for (int i = d.n; i < n; i++) {
int temp = a[i] + base;
ans.a[i] = temp % 10;
if (temp > 9) base = 1;
else base = 0;
}
}
ans.n = max(n, d.n);
if (base == 1) {
ans.a[n] = 1;
ans.n = ans.n + 1;
}
return ans;
}
Decimal operator + (int n) {
Decimal ans(n);
return *this + ans;
}
Decimal& operator ++ () {
*this = *this + 1;
return *this;
}
Decimal operator ++ (int) {
Decimal temp;
temp = *this;
*this = *this + 1;
return temp;
}
int getLength() { return n; }
int operator [] (int i) {
return a[n - 1 - i];
}
friend istream &operator >> (istream &in, Decimal &d) {
string s;
in >> s;
d.n = 0;
for (int i = s.size() - 1; i >= 0; i--) {
d.a[d.n++] = s[i] - '0';
}
return in;
}
friend ostream &operator << (ostream &os, const Decimal &d) {
for (int i = d.n - 1; i >= 0; i--) {
os << d.a[i];
}
return os;
}
};

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;
}