1. 程式人生 > >HDU 1002 A + B Problem II(兩個大數相加)

HDU 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

        分析:對於此題做法有兩種:其一,使2字串的中的字元數字減去'0',逐個相加大於等於10的可以使本位減10,下一位自增1,後面的處理就非常簡單了;其二,便是讀入字串後先讓各個字元減'0',一一對應存入整形陣列中;之後再相加。對於2種方法大致是相同的,都要從後面向前加,逢十進位,以及陣列初始化均要初始為0,一邊方便運算。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char a[1001]; //開闢兩個字元陣列a、b,作為兩個輸入的大數
char b[1001];
char c[1002];

int main(void)
{
    int carry = 0, n, j;
    int lena, lenb, i, lenc;

    scanf("%d", &n);
    for(j = 1; j <= n; j++)
    {
        memset(a, 0, 1001);
        memset(b, 0, 1001);
        memset(c, 0, 1002);
        scanf("%s", a);
        scanf("%s", b);
        lena = strlen(a);
        lenb = strlen(b);

        for(lena--, lenb--, i = 0, carry = 0; (lena >= 0) && (lenb >= 0); lena--, lenb--, i++)
        {
            c[i] = a[lena]-'0' + b[lenb]-'0' + carry;
            if((int)c[i] > 9)
            {
                c[i] = c[i] - 10 + '0';
                carry = 1;
            }
            else
            {
                c[i] += '0';
                carry = 0;
            }
        }

        while(lena >= 0)
        {
            c[i] = c[i] + a[lena] + carry; //有可能加上carry後還可以向前進位
            if(c[i] > '9')
            {
                c[i] -= 10;
                carry = 1;
            }
            else
                carry = 0;
            i++;
            lena--;
        }
        while(lenb >= 0)
        {
            c[i] = c[i] + b[lenb] + carry;
            if(c[i] > '9')
            {
                c[i] -= 10;
                carry = 1;
            }
            else
                carry = 0;
            i++;
            lenb--;
        }

        lenc = strlen(c);
        printf("Case %d:\n", j);
        printf("%s + %s = ", a, b);
        for(i = lenc-1; i >= 0; i--) //c陣列中c[0]存放的是大數的最低位,c[lenc-1]存放的是大數的最高位
            printf("%c", c[i]);
        printf("\n");
        if(j != n)
            printf("\n");
    }

    return 0;
}

參考資料: