Number of Digit One

原创 2015年11月18日 17:16:43

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 No.233 Number of Digit One

LeetCode No.233 Number of Digit One

leetcode解题笔记:Number of Digit One

233.Number of Digit One Given an integer n, count the total number of digit 1 appearing in all non...

[LeetCode]233.Number of Digit One

题目Given an integer n, count the total number of digit 1 appearing in all non-negative integers less ...

[分析总结:leetcode-Number of Digit One]寻找整数1到n之间所有数字中1出现的次数

leetcode原题链接:https://leetcode.com/problems/number-of-digit-one/ 题目描述: 要求寻找整数1到n之间所有数字中,1出现的次数。如给定...

Leetcode Number of Digit One

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

leetcode -- Number of Digit One -- 数学题,找规律

https://leetcode.com/problems/number-of-digit-one/参考http://www.cnblogs.com/grandyang/p/4629032.htmlh...

LeetCode-233.Number of Digit One

https://leetcode.com/problems/number-of-digit-one/ Given an integer n, count the total number o...

LeetCode Algorithms 233. Number of Digit One 题解

题目:Given an integer n, count the total number of digit 1 appearing in all non-negative integers less...

【LeetCode-Hard-2】【Number of Digit One】【1~N中‘1’出现次数】

第二题,中等难度,看到正确率略小于0.2就做了 233 Number of Digit One 19.5% Medium Given an integer n, count ...

[LeetCode]Number of Digit One,解题报告

题目Given an integer n, count the total number of digit 1 appearing in all non-negative integers less ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)