CCF NOI1020. 数字识别 (C++)

本文详细解析了一个简单的数字识别问题,通过输入一个不多于四位的正整数,程序能够判断并输出该数字的位数及每一位上的具体数字。提供了两种C++实现方案,一种是基于条件判断的逐位分解,另一种是使用数组存储逆序输出的方法。

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

1020. 数字识别

题目描述

输入一个不多于四位的正整数,求出它是几位数,并分别打印出各位上的数字。

输入

输入一个不多于四位的正整数x。

输出

第一行输出x的位数num,接下来num行从高位到低位输出x的每一位上的数字。

样例输入

123

样例输出

3
1
2
3

数据范围限制

1<=x<=9999

C++代码

#include <iostream>
#include <cassert>

using namespace std;

int main()
{
    int x;

    cin >> x;

    assert(x>=1 && x<=9999);

    if (x>=1 && x < 10)
    {
        cout << "1" << endl;
        cout << x << endl;
    }
    else if(x>= 10 && x<100)
    {
        cout << "2" << endl;
        cout << x/10 << endl;
        cout << x%10 << endl;
    }
    else if (x>=100 && x<1000)
    {
        cout << "3" << endl;
        cout << x/100 << endl;
        cout << (x%100)/10 << endl;
        cout << (x%100)%10 << endl;
    }
    else if (x >= 1000 && x<10000)
    {
        cout << "4" << endl;
        cout << x/1000 << endl;
        cout << (x%1000)/100 << endl;
        cout << ((x%1000)%100)/10 << endl;
        cout << ((x%1000)%100)%10 << endl;
    }

    return 0;
}

另一简洁的求解方法:

#include <iostream>
#include <cassert>
 
using namespace std;
 
int main()
{
    const int max_digits = 4;
    int digitsArray[max_digits];
    int numOfDigits = 0;
    
    int x;
 
    cin >> x;
 
    assert(x>=1 && x<=9999);
 
    while(x > 0)
    {
        digitsArray[numOfDigits++] = x ;
        x /= 10;
    }
 
    cout << numOfDigits << endl;

    for(int i=numOfDigits-1;i>=0; i--)
    {
        cout << digitsArray[i] << endl; 
    }
 
    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值