原题说明
Given an integer d
between 0
and 9
, and two positive integers low
and high
as lower and upper bounds, respectively. Return the number of times that d
occurs as a digit in all integers between low
and high
, including the bounds low
and high
.
Example 1:
Input: d = 1, low = 1, high = 13
Output: 6
Explanation:
The digitd=1
occurs6
times in1,10,11,12,13
. Note that the digitd=1
occurs twice in the number11
.
Example 2:
Input: d = 3, low = 100, high = 250
Output: 35
Explanation:
The digitd=3
occurs35
times in103,113,123,130,131,…,238,239,243
.
Note:
0 <= d <= 9
1 <= low <= high <= 2×10^8
解题思路
这道题我们用递归的方式,递归函数为recursiveCount(N, d)
, 将N
当中出现d
的次数分为个位数中出现的次数,加上非个位数出现的次数。
个位数出现的次数为N/10
, 非个位数中出现的次数为recursiveCount(N / 10, d) * 10
, 可以理解为N / 10
中每一个数都可以加后缀0 - 9成为N
中的一个数字。
当然还要考虑最后一位的大小,从而加减一个偏差,详见代码注释。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(log(N))
空间复杂度: O(1)
视频讲解
我们在Youtube上更新了视频讲解,欢迎关注!