统计指定数字总数的Python实现

2019-04-12  本文已影响0人  辛未

功能说明

统计指定范围[0, n]内所有的奇数数字中,3的数量总和。

实现代码

#!/usr/bin/python

def calcCountOfDigit3InBase(base):
    if base == 10: return 1
    return 10 * calcCountOfDigit3InBase(base / 10) + (base / 20)

def calcCountOfDigit3(n):
    base = 10
    while n / base > 0:
        base *= 10
    base /= 10

    count = 0
    while base >= 10:
        m = n / base
        count += m * calcCountOfDigit3InBase(base)
        if m > 3:
            count += base / 2
        if m == 3:
            count += ((n + 1) % base) / 2

        n = n % base
        base /= 10

    if n >= 3:
        count += 1
    return count

def printCountOfDigit3(n):
    print("%s = %s" % (n, calcCountOfDigit3(n)))

输出结果

printCountOfDigit3(800000000)
printCountOfDigit3( 60000000)
printCountOfDigit3(  6000000)
printCountOfDigit3(   200000)
printCountOfDigit3(    70000)
printCountOfDigit3(     8000)
printCountOfDigit3(      100)
printCountOfDigit3(       70)
printCountOfDigit3(        1)
printCountOfDigit3(866278171)

seewin@seewin:~$ python StatsCountOfDigit3.py 
800000000 = 410000000
60000000 = 29000000
6000000 = 2600000
200000 = 60000
70000 = 22500
8000 = 2100
100 = 15
70 = 12
1 = 0
866278171 = 441684627

不知结论正确与否,欢迎批评指正。

上一篇 下一篇

猜你喜欢

热点阅读