北大mooc,程序设计与算法(三)
题目
018:别叫,这个大整数已经很简化了!
程序填空,输出指定结果
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int MAX = 110;
class CHugeInt {
};
int main()
{
char s[210];
int n;
while (cin >> s >> n) {
CHugeInt a(s);
CHugeInt b(n);
cout << a + b << endl;
cout << n + a << endl;
cout << a + n << endl;
b += n;
cout << ++ b << endl;
cout << b++ << endl;
cout << b << endl;
}
return 0;
}
输入 多组数据,每组数据是两个非负整数s和 n。s最多可能200位, n用int能表示 输出 对每组数据,输出6行,内容分别是:
样例输入 99999999999999999999999999888888888888888812345678901234567789 12 6 6 样例输出 99999999999999999999999999888888888888888812345678901234567801 99999999999999999999999999888888888888888812345678901234567801 99999999999999999999999999888888888888888812345678901234567801 25 25 26 12 12 12 13 13 14
自己代码
大数加法,重载运算符
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int MAX = 110;
class CHugeInt {
private:
char s[210];
int v;
public:
CHugeInt(char c[]):v(0)
{
strcpy(s,c);
}
CHugeInt(int v_):v(v_)
{
memset(s, 0, sizeof(s));
}
char * Hugejia(char * a, char * b)
{
int c1[210];
int c2[210];
memset(c1, 0, sizeof(c1));
memset(c2, 0, sizeof(c2));
int len_a = strlen(a);
int len_b = strlen(b);
int max_l = len_a;
if(len_b > len_a)
max_l = len_b;
for(int i = 0; i < len_a; ++i)
c1[i] = a[len_a-i-1] - '0';
for(int i = 0; i < len_b; ++i)
c2[i] = b[len_b-i-1] - '0';
for(int i = 0; i <= max_l; ++i)
{
c1[i] += c2[i];
if(c1[i] > 9)
{
c1[i] -= 10;
++c1[i+1];
}
}
if(c1[max_l] != 0)
++max_l;
for(int i = 0; i <max_l; ++i)
b[i] = c1[max_l-i-1] + '0';
b[max_l] = '\0';
return b;
}
char * operator+ (CHugeInt & d)
{
static char c[210];
memset(c, 0, sizeof(c));
sprintf(c, "%d", d.v);
return this -> Hugejia(s, c);
}
friend char * operator+ (int n, CHugeInt & d)
{
static char c[210];
memset(c, 0, sizeof(c));
sprintf(c, "%d", n);
return d.Hugejia(d.s, c);
}
char * operator+ (int n)
{
static char c[210];
memset(c, 0, sizeof(c));
sprintf(c, "%d", n);
return this -> Hugejia(s, c);
}
void operator+= (int & n)
{
v = v + n;
}
int & operator++ ()
{
v = v + 1;
return v;
}
int operator++ (int k)
{
int temp = v;
v = v + 1;
return temp;
}
friend ostream & operator<< (ostream & os, const CHugeInt & d)
{
os << d.v;
return os;
}
};
int main()
{
char s[210];
int n;
while (cin >> s >> n) {
CHugeInt a(s);
CHugeInt b(n);
cout << a + b << endl;
cout << n + a << endl;
cout << a + n << endl;
b += n;
cout << ++b << endl;
cout << b++ << endl;
cout << b << endl;
}
return 0;
}
|