HDU-1002

来源:互联网 发布:proxifier for linux 编辑:程序博客网 时间:2024/06/01 11:44

A + B Problem II

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

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

Author
Ignatius.L

解题思路:本题是个大数问题,而我采用的方法是正面计算,这会容易出现一个不注意的问题,便是两个数组的数进行相加时位数没有对准确,注意两个数组相加是右对齐
解题代码

#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>#include<stdlib.h>using namespace std;int main(){    int T;    cin>>T;    int count1=0;    while(T--)    {        count1++;        char ch[1005],sh[1005];        int th[1005],vh[1005];        memset(ch,0,sizeof(ch));        memset(sh,0,sizeof(sh));        memset(th,0,sizeof(th));        memset(vh,0,sizeof(vh));        scanf("%s",ch);        scanf("%s",sh);        int len1=strlen(ch);        int len2=strlen(sh);        int k;        int l;        if(len1>len2)        {            k=len1;            l=len1-len2;            for(int i=1;i<=len1;i++)            {                th[i]=ch[i-1]-'0';            }            int j=1;            for(int i=1;i<=len1;i++)            {                if(i>l)                {                    vh[i]=sh[j-1]-'0';                    j++;                }            }        }        else        {            k=len2;            l=len2-len1;            for(int i=1;i<=len2;i++)            {                th[i]=sh[i-1]-'0';            }            int j=1;            for(int i=1;i<=len2;i++)            {                if(i>l)                {                    vh[i]=ch[j-1]-'0';                    j++;                }            }        }        for(int i=k;i>=1;i--)        {            if(vh[i]+th[i]>=10)                th[i-1]=th[i-1]+1;            th[i]=(vh[i]+th[i])%10;        }        printf("Case %d:",count1);        cout<<endl;        printf("%s + %s = ",ch,sh);        for(int i=0;i<=k;i++)        {            if(i==0&&th[i]==0)                continue;            printf("%d",th[i]);        }        cout<<endl;        if(T==0)            continue;        cout<<endl;    }    return 0;}
1 0