实现大整数类的加法

首先我们需要定义一个类,它支持传入的是整形,字符串,同时默认参数为0;
其次我们需要重载运算符+,=,重载输出流<<,同时重载输出流时,我们需要用friend定义友元,执行cout<<类的语句;
为了代码的简洁性,我们可以将整形转为字符串来储存。
代码如下

#include <iostream>
#include <string>
using namespace std;
class HugeInteger{
	private:
		string str;
	//定义成员变量
	public:
		HugeInteger(int i=0){
			int n=i,cnt=0;
			while(n){
				n/=10;
				cnt++;
			}
			//求是几位数
			for(int k=1;k<=cnt;k++){
				str=char(i%10+'0')+str;
				i/=10;
			}
			//实现从整形转化为字符串;
			if(cnt==0) str="0";
			//如果时0,我们需要特判一下,因为0是0位数
		}
		HugeInteger(string Str){
			str=Str;
		}
		friend ostream & operator<<( ostream & os,HugeInteger & c){
			os<<c.str;
			return os;
		}
		//友元导包输入输出流
		string operator + (const HugeInteger & c){
			string b=c.str;
			string a=this->str;
			while(a.size()>b.size()){
				b='0'+b;
			}
			while(a.size()<b.size()){
				a='0'+a;
			}
			a='0'+a;
			b='0'+b;
			for(int i=a.size()-1;i>=0;i--){
				a[i]=a[i]+b[i]-'0';
				if(a[i]>'9'){
					a[i]-=10;
					a[i-1]+=1;
				}
			}
			if(a[0]=='0') a=a.replace(0,1,"");
			return a;
		}
		//重载加号(类+类)
		string operator + (string a){
			string b=this->str;	
			while(a.size()>b.size()){
				b='0'+b;
			}
			while(a.size()<b.size()){
				a='0'+a;
			}
			a='0'+a;
			b='0'+b;
			for(int i=a.size()-1;i>=0;i--){
				a[i]=a[i]+b[i]-'0';
				if(a[i]>'9'){
					a[i]-=10;
					a[i-1]+=1;
				}
			}
			if(a[0]=='0') a=a.replace(0,1,"");
			return a;
		}
		//重载加号(类+字符串)
		HugeInteger operator = (string & a){
			HugeInteger box(a);
    		return box;
		}
		//重载等号
};
int main()
{
   HugeInteger n1( 7654321 );
   HugeInteger n2( 7891234 );
   HugeInteger n3( "99999999999999999999999999999" );
   HugeInteger n4( "1" );
   HugeInteger n5;
   cout << "n1 is " << n1 << "\nn2 is " << n2
      << "\nn3 is " << n3 << "\nn4 is " << n4
      << "\nn5 is " << n5 << "\n\n";
   n5 = n1 + n2;
   cout << n1 << " + " << n2 << " = " << n5 << "\n\n";
   cout << n3 << " + " << n4 << "\n= " << ( n3 + n4 ) << "\n\n";
   n5 = n1 + 9;
   cout << n1 << " + " << 9 << " = " << n5 << "\n\n";
   n5 = n2 + "10000";
   cout << n2 << " + " << "10000" << " = " << n5 << endl;

    return 0;
}
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值