关闭

Number of Digit One

163人阅读 评论(2) 收藏 举报
分类:

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21033次
    • 积分:829
    • 等级:
    • 排名:千里之外
    • 原创:65篇
    • 转载:3篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论