题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002
解题思路:利用数组进行大数的相加。内置数据类型不能满足整数位数的要求。
样例:
<span style="white-space:pre"> </span>1 999
<span style="white-space:pre"> </span>999 1
#include <iostream>
#include <cstring>
using namespace std;
int num1[1010],num2[1010];
int t[1010];
int result[1010];
char str1[1010],str2[1010];
void add(int len1,int len2)
{
int i,j;
//字符转换成数字,再反转
for(i = 0;i < len1;i++)
t[i] = str1[i] - 48;
for(i = len1 - 1,j = 0;i >= 0;i--,j++)
num1[j] = t[i];
for(i = 0;i < len2;i++)
t[i] = str2[i] - 48;
for(i = len2 - 1,j = 0;i >= 0;i--,j++)
num2[j] = t[i];
int k = 0,temp,cnt = 0;
i = 0;
while(i < len1 || i < len2)
{
temp = num1[i] + num2[i] + cnt;//cnt表示进位
if(temp >= 10)
{
cnt = 1;
result[i] = temp % 10;
}
else
{
result[k] = temp;
cnt = 0;
}
i++;
k++;
}
result[k] = cnt;//假如是99+99,则最后的进位1要记录下来
for(i = 0;i < len1;i++)
cout << str1[i];
cout << " + ";
for(i = 0;i < len2;i++)
cout << str2[i];
cout << " = ";
if(result[k] != 0)
cout << result[k];
int ii;
for(ii = k-1;ii >= 0;ii--)
{
cout << result[ii];
}
cout << endl;
}
int main(int argc, char *argv[])
{
int s,cnt = 1;
cin >> s;
int a = s;
while(s--)
{
memset(num1,0,sizeof(num1));
memset(num2,0,sizeof(num2));//每次都要初始化num1和num2 的数组,没有则会WA
memset(result,0,sizeof(result));
cin >> str1 >> str2;
cout << "Case " << cnt << ":" << endl;
add(strlen(str1),strlen(str2));
if(cnt < a) //最后的样例没有空行
cout << endl;
cnt++;
}
return 0;
}