Blog·Tanky WooABOUTRSS

HDOJ 1002 A + B Problem II

22 Jul 2010
这篇博客是从旧博客 WordPress 迁移过来,内容可能存在转换异常。

大数题之大数相加,经典的基础题~~

题目地址:

http://acm.hdu.edu.cn/showproblem.php?pid=1002

 // Author: Tanky Woo
// HDOJ 1002
// Accepted 1002 15MS 204K 1354B C++ Tanky Woo

#include 
#include 
using namespace std;
int nCases;
int m[1001], n[1001];
char a[1001], b[1001];
// www.wutianqi.com
int main()
{
    //freopen("input.txt", "r", stdin);
    scanf("%d", &nCases;);
    for(int i = 1; i <= nCases; ++i)
    {
        memset(m, 0, sizeof(m));
        memset(n, 0, sizeof(n));
        getchar();
        scanf("%s %s", a, b);
        int len1 = strlen(a);
        int len2 = strlen(b);
        if(len1 > len2)   //是m长度大于n
        {
            // 把字符数组a逆序转成int数组m
            int cnt = 0;
            for(int j = len1-1; j >= 0; --j)
                m[cnt++] = a[j] - '0';
            // 把字符数组b逆序转成int数组n
            cnt = 0;
            for(int j = len2-1; j >= 0; --j)
                n[cnt++] = b[j] - '0';
        }
        else
        {
            // 把字符数组a逆序转成int数组n
            int cnt = 0;
            for(int j = len1-1; j >= 0; --j)
                n[cnt++] = a[j] - '0';
            // 把字符数组b逆序转成int数组m
            cnt = 0;
            for(int j = len2-1; j >= 0; --j)
                m[cnt++] = b[j] - '0';
        }
        int len = len1 > len2? len2: len1;
        int k = 0;  //指示最高位

        for(int j = 0; j < len; ++j)
        {
            m[j] += n[j];
            if(m[j] >= 10)
                k = j+1;
            m[j+1] += (m[j]/10);
            m[j] %= 10;
        }
        printf("Case %d:\n", i);
        printf("%s + %s = ",a, b);
        len = len1>len2? len1: len2;
        if(k < len-1)
            k = len-1;
        for(int j = k; j >= 0; --j)
            printf("%d", m[j]);
        i == nCases? printf("\n"): printf("\n\n");
    }
    return 0;
}