大整数加法

#include <iostream>
#include <string>
#include <deque>
using std::cout;
using std::endl;
using std::deque;
using std::string;

class Solution
{
	public:
		string bigNumAdd(const string & a,const string & b){
			//--------------------
			//a,b格式:
			//1)a,b非空且都是数字字符
			//2)a,b不带正负符号
			//3)a,b没有前导0
			//如2342332,23300,0合法
			//+2322,-23423,0243不合法
			//由调用函数保证a,b的格式
			//--------------------
			int n1 = a.size();
			int n2 = b.size();
			int len = std::max(n1,n2);
			deque<char> result(len,0);
			char carry = 0;//进位
			int i = n1 - 1;
			int j = n2 - 1;
			int k = len - 1;
			//处理相重叠部分
			for(;i >=0 && j >=0;--i,--j,--k){
				result[k] = carry + toVal(a[i]) + toVal(b[j]);
				carry = result[k] / 10;
				result[k] %= 10;
			}
			//处理剩余部分
			while(i >= 0){
				result[k] = carry + toVal(a[i]);
				carry = result[k] / 10;
				result[k] %= 10;
				--i;
				--k;
			}
			while(j >= 0){
				result[k] = carry + toVal(b[j]);
				carry = result[k] / 10;
				result[k] %= 10;
				--j;
				--k;
			}
			//处理最后的进位
			while(carry > 0){
				result.push_front(carry % 10);
				carry /= 10;
			}
			//将result的结果转化成string返回
			string resultStr(result.size(),'0');
			for(size_t i = 0;i < result.size();++i){
				resultStr[i] += result[i];
			}
			return resultStr;
		}
	private:
		inline char toVal(char c){//数字字符转成其代表的值
			return c-'0';
		}
		bool isGE(const string & a,const string & b){
			if(a.size() != b.size()){
				return a.size() > b.size();
			}
			return a >= b;
		}
};

int main(){
	Solution sl;
	string a = "123456789";
	string b = "999999999";
	cout << sl.bigNumAdd(a,b) << endl;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值