A + B Problem II HDU1002

A + B Problem II  HDU1002

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

AC代码

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
const int maxn = 1050;
const int INF = 0x3f3f3f3f;
#define PI 3.1415927

int n, m;
int t;
char a[maxn], b[maxn], c[maxn];
int main()
{
    scanf("%d", &t);
    int q = 1;
    while(t--)
    {
        memset(a, 0, sizeof(a));//将a字符串全部填充0
        memset(b, 0, sizeof(b));
        memset(c, 0, sizeof(c));
        scanf("%s %s",a,b);
        int la = strlen(a);//获得字符串长度,下同
        int lb = strlen(b);
        reverse(a,a+la);//反转字符串,下同
        reverse(b,b+lb);
        int k = max(la, lb) +1;//取两者长的并且+1 +1是为了保证最高为进位正确
        int temp = 0;
        for(int i = 0; i < k; ++i)
        {
            if(a[i] && b[i])
                c[i] = a[i] + b[i] + temp - '0';//两加数均有效
            else
            {
                if(a[i])//仅a的加数有效
                c[i] = a[i] + temp;
                else
                {
                    if(b[i])//仅b的加数有效
                        c[i] = b[i] + temp;
                    else
                    {
                        if(!(a[i]||b[i]) && temp)//两加数均无效但temp有进位
                            c[i] = '0' + temp;
                    }
                }
            }
            if(c[i] >= '0' + 10)
            {
                c[i] -= 10;
                temp = 1;
            }
            else
            {
                temp = 0;
            }
        }
        int lc = strlen(c);
        if(!t)
        {
            printf("Case %d:\n", q++);
            reverse(a,a+la);//反转字符串,下同
            reverse(b,b+lb);
            reverse(c,c+lc);
            printf("%s + %s = %s\n", a, b, c);
        }
        else
        {
            printf("Case %d:\n", q++);
            reverse(a,a+la);
            reverse(b,b+lb);
            reverse(c,c+lc);
            printf("%s + %s = %s\n", a, b, c);
            printf("\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40758751/article/details/81274496
今日推荐