数0的数[1,2,... NUM] [英] Count number of 0s from [1,2,....num]

查看:120
本文介绍了数0的数[1,2,... NUM]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们给出了大量'NUM,其可具有高达10 ^ 4位数,(民&其中; = 10 ^(10000)),我们需要找到零的数的计数,在十进制再presentation从1高达数开始。

 如:
countZeros('9')= 0
countZeros('100')= 11
countZeros('219')= 41
 

我能想到的唯一的办法就是做蛮力,这显然是大投入太慢了。

我发现下面的蟒蛇code在这个链​​接,这确实在为O要求(L),L为对民的长度。

 高清CountZeros(NUM):
    Z = 0
    N = 0
    F = 0
    对于j中的xrange(LEN(NUM)):
        F = 10 * F + N  -  Z *(9-INT(NUM [J]))
        如果num [J] =='0':
            Z + = 1
        N = 10 * N + INT(NUM [J]。)
    回报˚F
 

我不明白背后it..Any怎样的帮助逻辑将AP preciated。

解决方案

  0  -  9:0零
从10  -  99:9的零(10,20,... 90)

--100-199解释-----------------------
100,101,...,109:11的零(2 100)
110,120,...,199:9零(这仅仅是一样10-99)这是一个重要的
总计:20
------------------------------------------

100  -  999:20 * 9 = 180

总数多达999:180 + 9:189
CountZeros(999) - > 189
 

Continu这种模式,你可能会开始看到的整体格局,最终的算法。

We are given a large number 'num', which can have upto 10^4 digits ,( num<= 10^(10000) ) , we need to find the count of number of zeroes in the decimal representation starting from 1 upto 'num'.

eg: 
countZeros('9') = 0
countZeros('100') = 11
countZeros('219') = 41

The only way i could think of is to do brute force,which obviously is too slow for large inputs.

I found the following python code in this link ,which does the required in O(L),L being length of 'num'.

def CountZeros(num):
    Z = 0
    N = 0
    F = 0
    for j in xrange(len(num)):
        F = 10*F + N - Z*(9-int(num[j]))
        if num[j] == '0':
            Z += 1
        N = 10*N + int(num[j])
    return F

I can't understand the logic behind it..Any kind of help will be appreciated.

解决方案

from 0 - 9 : 0 zeros
from 10 - 99: 9 zeros ( 10, 20, ... 90)

--100-199 explained-----------------------
100, 101, ..., 109 : 11 zeros (two in 100)
110, 120, ..., 199:  9 zeros (this is just the same as 10-99) This is important
Total: 20
------------------------------------------

100 - 999: 20 * 9 = 180 

total up to 999 is: 180 + 9: 189
CountZeros('999') -> 189 

Continu this pattern and you might start to see the overall pattern and eventually the algorithm.

这篇关于数0的数[1,2,... NUM]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆