您的位置:首页 > 其它

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

2014-03-27 21:16 417 查看

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 n, m ≤ 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));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  counting