数0的数[1,2,... NUM]

编程入门 行业动态 更新时间:2024-10-18 20:27:42
本文介绍了数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]

本文发布于:2023-06-08 21:29:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589390.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NUM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!