【 OJ 】 HDOJ1047 大数加法 [ 41 ]

36 篇文章 0 订阅
2 篇文章 0 订阅

思路大数相加,输入一系列大数,只需要不停的计算结果+输入大数就可,因此就是求2个大数相加

9+9=18,可知最多进位一个....

//简单的大数相加
# include<iostream>
# include<string>
using namespace std;
string result, temp;
string add(string a,string b) {
	if (a[0] == '0')return b;
	int alen = a.length();
	int blen = b.length();
	if (alen < blen) return add(b, a); 
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	//确保a>b
	int s=0,c=0,index=0;
	int aindex, bindex;//仅仅为了好监听...
	while (index < blen) {
		aindex = a[index]-'0'; bindex = b[index]-'0';
		s = aindex + bindex+c;
		a[index++] = (s % 10)+'0';
		c = s / 10;
	}
	while (c) {
		if (index < alen) {//无需进位
			aindex = a[index] - '0';
			s = aindex + c;
			a[index++] = (s % 10) + '0';
			c = s / 10;
		}
		else {//该进位一次
			char cc = c + '0';
			a += cc;
			c /= 10;
		}//9+9=18 最多一个进位
	}
	reverse(a.begin(), a.end());
	return a;
}
int main(void)
{
	int T;
	cin >> T;
	while (T--) {
		result = "0";
		cin >> temp;
		while (temp[0] != '0') {
			result = add(result, temp);
			cin >> temp;
		}
		cout << result << endl;
		if (T)
			cout << endl;
	}
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值