POJ 3286 How many 0's?

How many 0's?
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2844 Accepted: 1506

Description

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

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.

Output

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

Sample Output

1
22
92
987654304
3825876150

Source


  dp的思路很容易看出来,关键是处理好细节,调试了很长时间的代码。
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdio>
#define N 30
using namespace std;
__int64 dp1[N],dp2[N];
int dig[N];
int Top;
__int64 ba[N];
int main()
{
    //freopen("data.txt","r",stdin);
    __int64 f();
    memset(dp1,0,sizeof(dp1));
    memset(dp2,0,sizeof(dp2));
    dp1[1] = dp2[1] = 1;
    ba[0] = 1;
    ba[1] = 10;
    for(int i=2;i<=11;i++)
    {
        dp1[i] = dp2[i-1]*9;
        dp2[i] = 10*dp2[i-1]+ba[i-1];
        ba[i] = ba[i-1] * 10;
    }
    __int64 n,m;
    while(scanf("%I64d %I64d",&n,&m)!=EOF)
    {
        if(n<0)
        {
            break;
        }
        Top = 0;
        n-=1;
        __int64 res1,res2;
        if(n==-1)
        {
            res1 = 0;
        }else
        {
            if(n==0)
            {
                dig[Top++] = 0;
            }
            while(n!=0)
            {
               dig[Top++] = n%10;
               n = n/10;
            }
            res1=f();
        }
        Top = 0;
        if(m==0)
        {
            dig[Top++] = 0;
        }
        while(m!=0)
        {
            dig[Top++] = m%10;
            m = m/10;
        }
        res2 = f();
        printf("%I64d\n",res2-res1);
    }
    return 0;
}
__int64 f()
{
    __int64 res = 0;
    for(int i=1;i<=Top-1;i++)
    {
        res+=dp1[i];
    }
    //cout<<res<<endl;
    int t;
    for(int i=Top-1;i>=0;i--)
    {
        if(i==Top-1&&Top>1)
        {
            t = 1;
        }else
        {
            t = 0;
        }
        for(int j=t;j<=dig[i]-1;j++)
        {
            res+=dp2[i];
            if(j==0)
            {
                res+=ba[i];
            }
        }
    }
    for(int i=Top-1;i>=0;i--)
    {
        if(dig[i]==0)
        {
            __int64 sum = 0;
            for(int j=i-1;j>=0;j--)
            {
                sum = sum*10+dig[j];
            }
            sum+=1;
            res+=sum;
        }
    }
    return res;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值