题后感 005:别叫,这个大整数已经很简化了!

这个题目,真是让我为难了一天,在这里要好好检讨一下自己,遇到困难就怂了。浪费了一天时间,这种比较经典的题目,就算不会,背也要背下来。
主要难点在于,如何表示一个超大整数。指超过longlong的整数。
用数组的方法,依次存储个十百千。 相加时,低位依次相加,并判断进位。然后再反转输出。
此次学习了新函数

void *memset(void*s,int v,int size_n)

s是数组名或者指向某一空间的指针;此函数用来对一片内存空间逐字节进行初始化。
例如

	char s[210];
	memset(s,1,5);

就是用1,即0000 0001对其前五个字节进行初始化;

	int s[5];
	memset(s,1,20);

若是int类型,一个int四个字节全用0000 0001填充,则一个int就初始化得到数字16843009
除了字符串数组char s[],以外,其他数组的数组名放到cout<<后面,只会输出地址。
下面贴出老师给的标准答案:

#include <iostream> 
#include <cstring> 
#include <cstdlib> 
#include <cstdio> 
using namespace std;
const int MAX = 110; 
class CHugeInt {
	private:
		char buf[220];//固定一个220位大小的数组,便于进行对齐
	public:
		void reverse(char *p)//将存储数据的数组进行逆序操作,符合竖式计算从低位向高位进行的原理
		{
			int len=strlen(p)	;
			int i=0,j=len-1;
			while(i<j)
			{
				swap(p[i],p[j]);
				++i;
				--j;	
			}
		}
		CHugeInt(char *p)
		{
			memset(buf,0,sizeof(buf));//将buf初始化
			strcpy(buf,p);
			reverse(buf);
		}
		CHugeInt(int n)
		{
			memset(buf,0,sizeof(buf));
			sprintf(buf,"%d",n);
			reverse(buf);	
		}
		CHugeInt operator+(int n)
		{
			return *this+CHugeInt(n);//可以直接利用后面写的重载运算符	
		}
		CHugeInt operator+(const CHugeInt & n) const
		{
			CHugeInt tmp(0);
			int carry =0;//进位
			for(int i=0;i<210;i++)
			{
					char c1=buf[i];
					char c2=n.buf[i];
					if(c1==0&&c2==0&&carry==0)
						break;
					if(c1==0)
						c1='0';
					if(c2==0)
						c2='0';
					int k=c1-'0'+c2-'0'+carry;
					if(k>=10)//相加大于10则进位
					{
						carry=1;//进位位置1
						tmp.buf[i]=k-10+'0';
					}
					else
					{
						carry=0;
						tmp.buf[i]=k+'0';	
					}
			}
			return tmp;
		}
		friend CHugeInt operator+(int n,const CHugeInt & h)
		{
			return h+n;	
		}
		friend ostream & operator<<(ostream & o,const CHugeInt &h)//输出运算符重载
		{
			int len=strlen(h.buf);
			for(int i=len-1;i>=0;--i)
			cout<<h.buf[i];
			return o;	
		}
		CHugeInt &operator++()
		{
			*this=*this+1;
			return *this;	
		}
		CHugeInt operator++(int)
		{
			CHugeInt tmp(*this);
			*this=*this+1;
			return tmp;
		}
		CHugeInt &operator+=(int n)
		{
			*this=*this+n;
			return *this;	
		}
};
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;
	}
	system("pause");
	return 0;
}

关于++ --符号的重载;
为了与内置版本保持一致,前置+±- 应该返回对象的引用,后置+±-应该返回对象原值。
为了区别前置后置,后置运算符接受一个额外的(不被使用的)int类型的形参。

CHugeInt &operator++()//前置,返回引用,且无形参
		{
			*this=*this+1;
			return *this;	
		}
CHugeInt operator++(int)
		{
			CHugeInt tmp(*this);
			*this=*this+1;
			return tmp;
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值