Uva 11038 - How Many O's? 解题报告(计数)

本文详细介绍了如何通过编程解决计算指定范围内自然数中0的个数的问题,包括输入处理、分解数字、计算0的个数等步骤,并提供了相应的代码实现。适用于对算法和编程感兴趣的读者。

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

Problem E: How many 0's?

A Benedict monk No. 16 writes down the decimal representations of all natural numbers between and including m and nm ≤ n. How many 0's will he write down?

Input consists of a sequence of lines. Each line contains two unsigned 32-bit integers m and nm ≤ n. The last line of input has the value of m negative and this line should not be processed.

For each line of input print one line of output with one integer number giving the number of 0's written down by the monk.

Sample input

10 11
100 200
0 500
1234567890 2345678901
0 4294967295
-1 -1

Output for sample input

1
22
92
987654304
3825876150


    解题报告: 说实话,不喜欢这种题。一般思想不会太复杂,但是写起来还是很复杂的。代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>

typedef long long LL;

int digital[30];
int digitalNum=0;

LL ten[40];
LL num[40];
LL num2[40];
void init()
{
    for(int i=0;i<40;i++)
        ten[i] = pow(10, i)+0.5;

    num[0]=1;
    for(int i=1;i<40;i++)
        num[i]=num[i-1]*10+ten[i];

    num2[0]=1;
    for(int i=1;i<40;i++)
        num2[i]=num[i-1]*9;
}

void decomposition(LL n)
{
    digitalNum=0;
    while(n)
        digital[digitalNum++]=n%10,n/=10;
}

LL solve(LL n)
{
    if(n<0) return 0;
    if(n<10) return 1;

    decomposition(n);

    LL ans=(digital[digitalNum-1]-1)*num[digitalNum-2];
    for(int i=digitalNum-2;i>=1;i--)
    {
        if(digital[i]==0)
        {
            ans+=n%ten[i]+1;
            continue;
        }

        ans+=ten[i];
        ans+=digital[i]*num[i-1];
    }
    for(int i=0;i<digitalNum-1;i++)
        ans+=num2[i];
    ans++;
    return ans;
}

int main()
{
    init();

    LL m,n;
    while(~scanf("%lld%lld", &m, &n) && (~m || ~n))
        printf("%lld\n", solve(n)-solve(m-1));
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值