1002 A + B Problem II

发布时间: 更新时间: 总字数:268 阅读时间:1m 作者: IP上海 分享 网址
专栏文章

    1002 A + B Problem II

    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
    using
    namespace std;
    
    int
    main()
    {
         int k, n, l1, l2, l;
         int n1[1002], n2[1002];
         char str1[1002], str2[1002];
         cin>>n;
         k=n;
         while(k--)
         {
                memset(n1, 0, sizeof(n1));
                memset(n2, 0, sizeof(n2));
                cin>>str1;
                cin>>str2;
                l1=strlen(str1);
                l2=strlen(str2);
                if(l1>l2)
                       l=l1;
                else
                       l=l2;
                for(int i=l1-1, j=0; i>=0; i--, j++)
                       n1[j]=str1[i]-'0';
                for(i=l2-1, j=0; i>=0; i--, j++)
                       n2[j]=str2[i]-'0';
                for(i=0; i
                {
                       n1[i]+=n2[i];
                       if(n1[i]>9)
                       {
                            n1[i+1]+=n1[i]/10;
                            n1[i]=n1[i];
                       }
                }
    
                n1[l-1]=n1[l-1]+n2[l-1];
                if(n1[l-1]>9)
                {
                       l++;
                       n1[l-1]+=n1[l-2]/10;
                       n1[l-2]=n1[l-2];
                }
                char s[1002];
                for(i=l-1, j=0; i>=0; i--, j++)
                       s[j]=n1[i]+'0';
                s[l]='\0';
                cout<<"Case "<<n-k<<":"<<endl;
                cout<<str1<<" + "<<str2<<" ="<<s<<endl;
                if(k!=0)
                       cout<<endl;
         }
         return 0;
    }
    
    Home Archives Categories Tags Statistics
    本文总阅读量 次 本站总访问量 次 本站总访客数