018:别叫,这个大整数已经很简化了

这篇博客详细介绍了如何在C++中实现大整数的加法操作,包括使用字符数组存储大整数、反转数组以进行加法计算以及实现大整数类的构造函数、友元函数等。通过示例展示了大整数与整数相加的运算符重载,以及自增运算符的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream> 
#include <cstring> 
#include <cstdlib> 
#include <cstdio> 
using namespace std;
const int MAX = 110; 
class CHugeInt {
	private:
		char buf[220];
		void reverse()
		{
			int tmp;
			int len = strlen(buf);
			for (int i = 0; i < len / 2; i ++)
			{
				tmp = buf[i];
				buf[i] = buf[len - 1 - i];
				buf[len - 1 - i] = tmp;
			}
		}
	public:
		CHugeInt(int n)
		{
			memset(buf, 0, sizeof(buf)); 
			sprintf(buf, "%d", n);
			reverse();
		}
		
		CHugeInt(char *s)
		{
			memset(buf, 0, sizeof(buf));
			strcpy(buf, s);
			reverse();
		} 
		
		CHugeInt operator+(const CHugeInt b){//必须要有const 
			CHugeInt tmp(0);
			
			int lena = strlen(buf), lenb = strlen(b.buf); 
			int len = max(lena, lenb);
			
			int t = 0, i;
			for (i = 0; i < len; i ++)
			{
				if (i < lena) t = t + buf[i] - '0';
				if (i < lenb) t = t + b.buf[i] - '0';
				tmp.buf[i] = t % 10 + '0';
				t /= 10;
			}
			if (t) tmp.buf[i] = t + '0';
			return tmp;
		}
		
		CHugeInt operator+(int n)
		{
//			CHugeInt tmp(n);
//			return *this + tmp; //	CHugeInt operator+(const CHugeInt b)可以没有const 
			
			return *this + CHugeInt(n);	
		} 
		
		friend CHugeInt operator+(int n,CHugeInt &a)
		{
			return a + n;
		}
		
		friend ostream & operator<<(ostream &o, const CHugeInt &a)//必须要有cosnt,没有const可以输出cout<<a;不能cout<<a+b; 
		{
			int len = strlen(a.buf);
			for (int i = len - 1; i >= 0; i --)
				cout << a.buf[i];
			return o;
		}
		
		CHugeInt operator++()
		{
			*this = *this + 1;
			return *this;
		}
		CHugeInt operator++(int k)
		{
			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;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值