Number of Digit One

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:
Given n = 13,

Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

3141092 a = 31410,b = 92, 百位上1的个数为3141个100

3141192 a = 31411,b = 92, 百位上1的个数为3141个100,外加100~192这93个数

3141594, a = 31415, b = 94,百位上1的个数为3141个100,外加100~199这100个数

总的公式(a+8) / 10 * m + (a % 10 == 1) * (b + 1)

class Solution(object):
    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: int
        """
        m = 1
        sum = 0
        while m <= n:
            a = n / m
            b = n % m
            sum += (a+8) / 10 * m 
            if a % 10 == 1:
                sum += (b + 1)
            m *= 10
        return sum


阅读更多
个人分类: leetcode
上一篇Remove Linked List Elements
下一篇tensorflow学习踩坑
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭