问题链接:HDU-1002
问题简述
第一行输入一个正整数n,表示有n组数据,每组数据一行,每行2个位数不超过1000的正整数,计算出这两个数的和,并按要求输出。
思路
高精度运算,数字过大,所以用字符串来储存,一位一位相加,最后再输出。
AC通过的C++语言程序如下:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
string a, b, a1, b1; vector<int> c; int na, nb, t = 0;
cin >> a >> b;
a1 = a; b1 = b;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
na = a.size(); nb = b.size();
if (na > nb)
for (int j = 0; j < na - nb; j++)
b = b + '0';
if (na < nb)
for (int j = 0; j < nb - na; j++)
a = a + '0';
for (int j = 0; j<a.size(); j++)
{
int d;
d = a[j] + b[j] - 96 + t;
t = 0;
if (d < 10) c.push_back(d);
else { d = d - 10; c.push_back(d); t = 1; }
}
if (t == 1) c.push_back(1);
cout << "Case " << i + 1 << ":" << endl;
cout << a1 << " + " << b1 << " = ";
for (int j = c.size()-1; j >= 0; j--)
cout << c[j];
cout << endl;
if (i != n - 1) cout << endl;
}
return 0;
}