[CodeVS 1166] 高精度加法

本文介绍了一个手动实现的大整数类BigInteger,支持基本的加法运算和大小比较功能。该类使用字符串来存储数值,通过重载运算符实现加法及大小比较等操作。

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


 

先弄个支持加减和大小比较的manual BigInteger 

#include<bits/stdc++.h>
using namespace std;

class BigInteger
{
	public:
		string num;
		BigInteger ()	{ num="0" ;}
		BigInteger & operator = (const BigInteger & that ) { num=that.num; }
		bool operator > (const BigInteger & that ) {
			if(num.length()!=that.num.length()) return num.length()>that.num.length();
			else return num>that.num;
		}
		BigInteger operator + (const BigInteger & that ) const {
			string s1=num,s2=that.num;
			if(s1.length()<s2.length()) swap(s1,s2);
			int size=s1.length()+1;
			int a[s1.length()],b[s2.length()],c[size];
			for(register int i=0;i<s1.length();i++) a[i]=s1[s1.length()-1-i]-'0';
			for(register int i=0;i<s2.length();i++) b[i]=s2[s2.length()-1-i]-'0';
			memset(c,0,sizeof c);
			for(register int i=0;i<s1.length();i++){
				i<s2.length()?c[i]=a[i]+b[i]:c[i]=a[i];
				c[i+1]=c[i]/10;
				c[i]%=10;
			}
			BigInteger res;
			for(register int i=size-1;i>=0;i--){
				res.num.push_back(c[i]+'0');
			}
			while(res.num.length()>1&& res.num[0]=='0') res.num.erase(0,1);
			return res;
		} 
};


int main()
{
	BigInteger buffer,tot;
	cin>>tot.num;
	while(cin>>buffer.num)
	{
		tot=tot+buffer;
		cout<<tot.num;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值