(leetcode233)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.

Example:

Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.


这里的11含有两个1,所以输出为6.
今天尝试了一道hard难度的题,还是挺虐心的,花了一个多小时,不过好在击败了100%的python3用户。
在这里插入图片描述

代码如下:

class Solution:
    def countWeight(self, ns, i):
        w = len(ns) - i - 1
        a = int(ns[i])
        if a == 1:
            if w==0:
                return 1
            tail = int(ns[i + 1:]) + 1 if i + 1 < len(ns) else 0
            res = w * pow(10, w - 1) + tail
            return res
        else:
            if w > 0 and a > 0:
                res = w * pow(10, w - 1) * a + pow(10, w)
            else:
                res = 1 if a > 0 else 0
            return res
    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n<0: return 0
        ns = str(n)
        width = len(ns)
        res = 0
        for i in range(width):
            res += self.countWeight(ns, i)
        return int(res)
        

编这道题需要打大量的数学草稿,其实就是披着编程外套的数学题。

猜你喜欢

转载自blog.csdn.net/leviopku/article/details/82997752