现在的位置: 首页 > 综合 > 正文

大数相加

2018年05月22日 ⁄ 综合 ⁄ 共 2130字 ⁄ 字号 评论关闭

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

#include<stdio.h>
void
sub(char a[],char b[]);
main
()
{

    char
a[1000],b[1000];
    int
n,i;
    scanf("%d",&n);
    for
(i=0;i<n;i++)
    {

    scanf("%s %s",&a,&b);
    if
(i>0)
    printf("/n");
    printf("Case %d:/n",i+1);
    printf("%s + %s = ",a,b);
    sub(a,b);
    }
   
}

void
sub(char  * a,char * b)
{

    int
lenA,lenB,i,k,flag=0,r,m;
    int
c[1001];
    for
(m=0;m<1001;m++)
        c[m]=0;
    lenA=strlen(a);lenB=strlen(b);
    k=lenA>lenB?lenA:lenB;
    r=k;
    while
(lenA>0&&lenB>0)
    {

        c[k]=a[lenA-1]+b[lenB-1]+flag-96;
        if
(c[k]>9)
        {

            c[k]=c[k]%10;
            flag=1;
        }

        else

        {

            flag=0;
        }

        k--;lenA--;    lenB--;
       
    }

   if
(lenA>lenB)
      {

        for
(i=lenA-1;i>=0;i--,k--)
        {

            c[k]=a[i]-48+flag;
            if
(c[k]>9)
            {

                c[k]=c[k]%10;
                flag=1;
            }

            else

            {

                flag=0;
            }
        }
    }

    else if
(lenA<lenB)
    {

        for
(i=lenB-1;i>=0;i--,k--)
        {

            c[k]=b[i]-48+flag;
            if
(c[k]>9)
            {

                c[k]=c[k]%10;
                flag=1;
            }

            else

            {

                flag=0;
            }
        }
    }
else
    {

        if
(flag==1)
            c[k]=1;
    }

   
    if
(c[0]==0)
    {

        for
(i=0;i<=r;i++)
        {

        c[i]=c[i+1];
        }

        r--;
    }

    for
(i=0;i<=r;i++)
        printf("%d",c[i]);
    printf("/n");
}

【上篇】
【下篇】

抱歉!评论已关闭.