大数A + B Problem II-hdu-1002
A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 165447 Accepted Submission(s): 31605
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
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
解题思路:
大数问题,用数组存取。先用字符串输入,然后保存在int数组里面进行加减。
注意:1。加法进位最大进 1;2、输出格式很重要,尤其是没两组数据后空一行,但最后组数据后,结果不空行。
#include<stdio.h>
#include<string.h>
#define N 1100
int main()
{
int a[N],b[N],s[N],i,j,n,m,k,t,T,r;
char c[N],d[N];
scanf("%d",&T);r=0;
while(T--)
{
scanf("%s %s",c,d);
r++;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
m=strlen(c);
n=strlen(d);
for(i=0,j=m-1;i<m;i++)// 分别把两个字符串输入到 整形数组里面。注意 是倒叙存取。
{ a[i]=c[j]-'0';j--;}
for(i=0,j=n-1;i<n;i++)
{ b[i]=d[j]-'0';j--;}
if(m<n) //找出最长的字符串。
k=n;
else
k=m;
for(i=0,t=0;i<=k;i++)
{
s[i]=(a[i]+b[i]+t)%10;// 分别相加,取个位。 t 代表进位的数字
if((a[i]+b[i]+t)>9)
t=1; // 因为加法 只能进1 或者不进为(也是进0).
else
t=0;
}
if(s[k]==0) //判断最高位是否为零,为零则不输出。
k--;
printf("Case %d:\n%s + %s = ",r,c,d);
for(i=k;i>=0;i--) // 倒叙输出,先输出最高位。
printf("%d",s[i]);
if(T>0) //是否是最后一次执行。
printf("\n\n");
else
printf("\n");
}
return 0;
}