HDOJ A + B Problem II 大数相加问题

来源:互联网 发布:有机合成工艺优化理由 编辑:程序博客网 时间:2024/05/15 00:56

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 371552    Accepted Submission(s): 72414


Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
 

Sample Input
21 2112233445566778899 998877665544332211
 

Sample Output
Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110
 

Author

Ignatius.L

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int T,i,j,flag=0;
char str1[1010],str2[1010];
int a[1020];
scanf("%d",&T);
int m=T;//注意将T赋值给一个固定的变量,最后循环时候直接等于T不正确(T在变) 
while(T--)
{
flag++;
int k=0;
memset(str1,0,sizeof(str1));
memset(str2,0,sizeof(str2));
memset(a,0,sizeof(a));
scanf("%s %s",str1,str2);
int len1=strlen(str1);
int len2=strlen(str2);
for(i=len1-1,j=len2-1;i>=0&&j>=0;i--,j--)//开始相加 
{
if(a[k]+(str1[i]-'0')+(str2[j]-'0')>=10)
{
a[k]=a[k]+(str1[i]-'0')+(str2[j]-'0')-10;
a[k+1]++;
}
else
a[k]=a[k]+(str1[i]-'0')+(str2[j]-'0');
k++;
}
if(i>=0)//str1数组中存的数比str2中存的数长
{
while(i>=0)
{
a[k]=a[k]+(str1[i]-'0');
i--;
k++;
}

else if(j>=0)//str2数组中存的数比str1中存的数长
{
while(j>=0)
{
a[k]=a[k]+(str2[j]-'0');
j--;
k++;
}
}
else//str1数组中存的数和str2数组中存的数长度相同 
{
if(a[k]!=0)
k++;
}
printf("Case %d:\n",flag);//从这里往下主要是细节 
printf("%s + %s = ",str1,str2);//不要忘了空格,否则presentation error(输出格式错误) 
for(int t=k-1;t>0;t--)
printf("%d",a[t]);
printf("%d\n",a[0]);
if(flag!=m)//注意最后一组数据后不需要换行 
printf("\n");
}
return 0;
}

原创粉丝点击