题目:原题链接(困难)

标签:数学、动态规划

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( l o g N ) O(logN) O(logN) O ( 1 ) O(1) O(1) 40ms (100.00%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Solution:
    def digitsCount(self, d: int, low: int, high: int) -> int:
        return self.count(high, d) - self.count(low - 1, d)

    def count(self, num, d):
        ans = 0
        i = 1
        while i <= num:
            # 这一位以上的总数
            high = num // (i * 10)

            # 这一位当前的值
            now = num // i % 10

            # 这一位以下的总数
            low = num % i

            # 基础情况:这一位以上的总数乘以当前位的位置
            ans += high * i

            # 当前位大于d:当前位=d的情况一定存在,额外加上当前位的1
            if now > d:
                ans += 1 * i

            # 当前位小于d:
            elif now < d:
                pass

            # 当前位等于d:更小的都会有这一位的d
            else:
                ans += low + 1

            # 如果d为0,这一位不能用于开头
            if d == 0:
                ans -= i

            i *= 10

        return ans