HDU 1002 A + B Problem II

来源:互联网 发布:乐视有没有mac版 编辑:程序博客网 时间:2024/05/16 03:36

A + B Problem II

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


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


杭电初级题,大数相加。

我最直接的思路,先设置输入数组为char型,输入一连续的数,遇到非数字字符断开,再输入一行数字,然后把两个字符数组里的char型数字转化成int型数字放到int型数组里,两个int型数组逐位倒序相加,大于9则进位。

#include <stdio.h>#include <string.h>char a[10000]={0},b[10000]={0},sum[10000]={0},a1[10000]={0},b1[10000]={0};int main(){ int i,j,t,lena,lenb,k; while(scanf("%d",&t)!=EOF) {     for(i=0;i<t;i++)     {        scanf("%s%s",a,b);         lena=strlen(a);         lenb=strlen(b);         k=0;         for(j=lena-1;j>=0;j--)         {             a1[k++]=a[j]-'0';         }         k=0;         for(j=lenb-1;j>=0;j--)         {             b1[k++]=b[j]-'0';         }         j=0;         while(j<=lena||j<=lenb)         {             if(sum[j]+a1[j]+b1[j]>=10)             {                 sum[j+1]=sum[j+1]+1;                 sum[j]=sum[j]+a1[j]+b1[j]-10;             }             else             sum[j]=sum[j]+a1[j]+b1[j];                 j++;         }         printf("Case %d:\n",i+1);         printf("%s + %s = ",a,b);         if(sum[j-1])         {             for(k=j-1;k>=0;k--)              printf("%d",sum[k]);         }        else         {             for(k=j-2;k>=0;k--)             printf("%d",sum[k]);         }         printf("\n");         if(i<t-1)         printf("\n");        memset(a,0,sizeof(sum));        memset(b,0,sizeof(sum));        memset(a1,0,sizeof(sum));        memset(b1,0,sizeof(sum));        memset(sum,0,sizeof(sum));     } }    return 0;}

这道题还有其他做法,比如链表等。

2 0