杭电oj刷题——1002(大数加法)

杭电oj刷题——1002(大数加法)

问题描述:
杭电oj刷题——1002(大数加法)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002
Sample Input
2
1 2
112233445566778899 998877665544332211

Sample Output
Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

#include<iostream>
#include<string.h>
#define max 1000
using namespace std;
int main()
{
    char a[max + 1], b[max + 1], temp;
    int len1, len2, n, i, j, _count, cnt[max + 1] = {0};
    cin >> n;
    int count1 = 0;
    while(n--)
    {
        _count = 0;
        count1++;
        memset(cnt,0,sizeof(cnt));//输出数组cnt清零
        cin >> a >> b;
        len1 = strlen(a);
        len2 = strlen(b);
        cout << "Case " << count1 << ":" << endl;
        for(i = 0; i < len1; i++)
            cout << a[i];
        cout << " + ";
        for(i = 0; i < len2; i++)
            cout << b[i];
        cout << " = ";
        for(i = len1 - 1, j = len2 - 1; i >= 0 && j >= 0; i--, j--)
        {
            temp = a[i] + b[j] + cnt[_count];
            if(temp >= '5' * 2)//相同位结果大于等于10
            {
                cnt[_count] = temp - '5' * 2;
                cnt[++_count] = 1;//进位
            }
            else
                cnt[_count++] = temp - '0' * 2;//将char型数据转化为int型
        }
        while(i >= 0)
        {
            temp = a[i] + cnt[_count];
            if(temp >= '5' * 2)
            {
                cnt[_count] = temp - '5' * 2;
                cnt[++_count] = 1;
            }
            else
                cnt[_count++] = temp - '0';//将char型数据转化为int型
            i--;
        }
        while(j >= 0)
        {
            temp = b[j] + cnt[_count];
            if(temp >= '5' * 2)
            {
                cnt[_count] = temp - '5' * 2;
                cnt[++_count] = 1;
            }
            else
                cnt[_count++] = temp - '0';//将char型数据转化为int型
            j--;
        }思路
        if(cnt[_count] == 0)//判断最后一个是否有进位
            _count = _count - 1;
        for(i = _count; i >= 0; i--)
            cout << cnt[i];
        cout << endl;
        if(n != 0)//除了最后一行外其他行数据要换行
            cout << endl;
    }
    return 0;
}

整体思路:由于数据过大,无法用long long型数据来装载输入数据,因此使用char型数组来装载,然后根据加法的规则,对两个输入数据进行简单加法模拟,在这个过程中要注意char型数据和int型数据的转化。
注意:输出格式时最后一行数据不要换行多次,否则会出现格式错误!!!