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

本文提供了一种解决杭电OJ 1002题(大数加法)的有效方法,通过使用char型数组装载数据,避免了long long型数据的限制。文章详细解释了如何对两个输入数据进行加法模拟,并注意到了char型和int型数据之间的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

杭电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型数据的转化。
注意:输出格式时最后一行数据不要换行多次,否则会出现格式错误!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值