杭电OJ 1002 大数相加

#include <iostream>
#include <string>
using namespace std;
int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		string a, b;
		cin >> a >> b;
		cout << "Case " << i + 1 << ":" << endl;
		cout << a << " + " << b << " = ";
		int an = (int)a.size();
		int bn = (int)b.size();
		int sub = an - bn;
		if (sub > 0)
		{
			string c(sub, '0');
			b = c + b;
		}
		if (sub < 0)
		{
			string c(-sub, '0');
			a = c + a;
		}
		a = '0' + a;
		b = '0' + b;

		an = (int)a.size();
		string sum(an, '0');
		int e = 0;
		for (int j = an-1; j >=0; j--)
		{
			int d = a[j] - '0' + b[j] - '0' + e;
			e = 0;
			if (d >= 10)
			{
				d -= 10;
				e = 1;
			}
			sum[j] = d + '0';
		}
	
		if (sum[0] != '0')
			cout << sum[0];
		for (int j = 1; j < an; j++)
			cout << sum[j];
		cout << endl;
		if (i != n - 1)
			cout << endl;
	}
	return 0;
}
数字每一位分别相加组成字符串

猜你喜欢

转载自blog.csdn.net/fuwu4087/article/details/80715250