def count_nines(n):
if n==0:
return 0
k = len(str(n))-1
leading_digit, remainder = divmod(n, 10**k) # Thanks @Stef for this optimization
# Number of nines in numbers from 1 to leading_digit * 10**k - 1
count1 = leading_digit * k*10**(k-1)
# If the leading_digit is 9, number of times it appears
# (in numbers from 9 * 10**k to n)
count2 = remainder+1 if leading_digit==9 else 0
# Number of nines in remainder
count3 = count_nines(remainder)
# Total number of nines
return int(count1 + count2 + count3)
1条答案
按热度按时间mf98qq941#
下面是基于我的评论的一些工作代码(我在一些不太大的数字上测试了它,它返回的结果与您的相同):
解释
示例