2021-20-21-leetcode数字1的个数

2021-20-21-leetcode数字1的个数

给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。 https://leetcode-cn.com/problems/number-of-digit-one/

于是我写出了这个


class Solution:
    def countDigitOne(self, n: int) -> int:
        return sum(str(i).count("1") for i in range(1, n+1))

超时了

我打印1~100之间1的个数是有规律了

when is 0, answer is 0 when is 1, answer is 1 when is 2, answer is 1 when is 3, answer is 1 when is 4, answer is 1 when is 5, answer is 1 when is 6, answer is 1 when is 7, answer is 1 when is 8, answer is 1 when is 9, answer is 1 when is 10, answer is 2 when is 11, answer is 4 when is 12, answer is 5 when is 13, answer is 6 when is 14, answer is 7 when is 15, answer is 8 when is 16, answer is 9 when is 17, answer is 10 when is 18, answer is 11 when is 19, answer is 12 when is 20, answer is 12 when is 21, answer is 13 when is 22, answer is 13 when is 23, answer is 13 when is 24, answer is 13 when is 25, answer is 13 when is 26, answer is 13 when is 27, answer is 13 when is 28, answer is 13 when is 29, answer is 13 when is 30, answer is 13 when is 31, answer is 14 when is 32, answer is 14 when is 33, answer is 14 when is 34, answer is 14 when is 35, answer is 14 when is 36, answer is 14 when is 37, answer is 14 when is 38, answer is 14 when is 39, answer is 14 when is 40, answer is 14 when is 41, answer is 15 when is 42, answer is 15 when is 43, answer is 15 when is 44, answer is 15 when is 45, answer is 15 when is 46, answer is 15 when is 47, answer is 15 when is 48, answer is 15 when is 49, answer is 15 when is 50, answer is 15 when is 51, answer is 16 when is 52, answer is 16 when is 53, answer is 16 when is 54, answer is 16 when is 55, answer is 16 when is 56, answer is 16 when is 57, answer is 16 when is 58, answer is 16 when is 59, answer is 16 when is 60, answer is 16 when is 61, answer is 17 when is 62, answer is 17 when is 63, answer is 17 when is 64, answer is 17 when is 65, answer is 17 when is 66, answer is 17 when is 67, answer is 17 when is 68, answer is 17 when is 69, answer is 17 when is 70, answer is 17 when is 71, answer is 18 when is 72, answer is 18 when is 73, answer is 18 when is 74, answer is 18 when is 75, answer is 18 when is 76, answer is 18 when is 77, answer is 18 when is 78, answer is 18 when is 79, answer is 18 when is 80, answer is 18 when is 81, answer is 19 when is 82, answer is 19 when is 83, answer is 19 when is 84, answer is 19 when is 85, answer is 19 when is 86, answer is 19 when is 87, answer is 19 when is 88, answer is 19 when is 89, answer is 19 when is 90, answer is 19 when is 91, answer is 20 when is 92, answer is 20 when is 93, answer is 20 when is 94, answer is 20 when is 95, answer is 20 when is 96, answer is 20 when is 97, answer is 20 when is 98, answer is 20 when is 99, answer is 20

官方解时

考虑统计1位的数据,然后组装

Loading Disqus comments...
Table of Contents