简体   繁体   中英

How do I count the number of specific digits in an integer

I want to make a program so that it counts the total number of 6's between two integers.

For example the total number of 6's that appear from 1 to 99 is 20.

How would I make this for larger numbers on python?

Would appreciate help!

I'd do it with sum and count :

>>> sum(str(n).count("6") for n in range(1, 100))
20
>>> sum(str(n).count("6") for n in range(1, 100000))
50000
>>> sum(str(n).count("6") for n in range(1, 10000000))
7000000

For much larger numbers you might need to come up with some clever algorithmic trick rather than actually doing it as a linear operation. I can roughly envision something with recursion and memoization that involves getting the answer for a smaller subset of the digits, multiplying it by 10 for each of the 10 digits that can be combined with it, and then adding 1 for the 6 that occurs in one of those possibilities, but if you don't actually need to do this for numbers that greatly exceed a million I wouldn't bother.

这里有一些可能对你有用的东西,我不知道你想要解析多大的数字......

str(list(range(1, 1000000))).count('6')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM