输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
限制:
1 <= n < 2^31
一开始想简单统计str的1的个数,超时
class Solution:
def countDigitOne(self, n: int) -> int:
result = 0
for i in range(1, n+1):
if '1' in str(i):
result += str(i).count('1')
return result
接下来找规则,
例如1234,将其分为高位high=1和其他last=234,根据高位确定最大拆分除数p=1000
要求F(1234),
按范围划分,
0~999:F(p-1)
1000~1234:此时由于高位是1,所以高位中1出现了last+1次,非高位为F(last)
结果为 F(p-1) + last+1 + F(last)
对于高位不是1的情况,如2345,high=2,last=345,p=1000
范围:
0~999:F(p-1)
1000~1999:高位p,非高位F(p-1)
2000~2345:F(last)
结果为 F(p-1) + p + F(p-1) + F(last)
总结规律为:
当high=1:F(p-1) + last+1 + F(last)
否则:high*F(p-1) + p + F(last)
递归出口为0
class Solution:
def countDigitOne(self, n: int) -> int:
if n == 0:
return 0
p = 10**(len(str(n))-1)
last = n % p
high = n // p
if high == 1:
add = last + 1
else:
add = p
return high*self.countDigitOne(p-1) + add + self.countDigitOne(last)