【 OJ 】 HDOJ1047 18年12月15日21:00 [ 41 ]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QingCoffe/article/details/85018439

思路大数相加,输入一系列大数,只需要不停的计算结果+输入大数就可,因此就是求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;
}

猜你喜欢

转载自blog.csdn.net/QingCoffe/article/details/85018439