题解 | #整数中1出现的次数(从1到n整数中1出现的次数)#Python统计各位上的次数

整数中1出现的次数(从1到n整数中1出现的次数)

http://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6

# -*- coding:utf-8 -*-
import math
class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        # write code here
        if n == 0:
            return 0
        num = math.floor(math.log(n, 10)) #统计位数:个位0,十位1,百位2
        summ = 0 #统计1的个数
        head = 0 #统计某一位数时高位的数值,如2105,统计千位时高位为0,统计十位时高位为21.
        half = n #统计某一位数时的余数,如2105,统计千位时为2105,统计百位时为105.
        for i in range(num, -1, -1):
            x = pow(10, i)
            if half //x == 1:
                summ += half % x + 1 + head*x 
                #统计位数为1时,百位为1,余数half=05,[100-105]共6个数,高位head=2,[0100-0199,1100-1199]共200个数
            elif half // x == 0:
                summ += head*x
                #统计位数小于1时,十位为0,高位head=21,此时仅考虑[00-20]为21个数,不考虑21
            else:
                summ += (head+1)*x
                #统计位数大于1时,千位为2,高位head=0,可包含千位为1,即[1000-1999]为1k个数
            half = half % x
            head = n // x
        return summ
全部评论

相关推荐

海螺很能干:每次看到这种简历都没工作我就觉得离谱
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务