[Swift]LeetCode1067. 范围内的数字计数 | Digit Count in Range
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ )
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10961687.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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 = 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 = 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
给定一个在 0
到 9
之间的整数 d
,和两个正整数 low
和 high
分别作为上下界。返回 d
在 low
和 high
之间的整数中出现的次数,包括边界 low
和 high
。
示例 1:
输入:d = 1, low = 1, high = 13 输出:6 解释: 数字d=1
在1,10,11,12,13 中出现 6 次
。注意d=1
在数字 11 中出现两次。
示例 2:
输入:d = 3, low = 100, high = 250 输出:35 解释: 数字d=3
在103,113,123,130,131,...,238,239,243 出现 35 次。
提示:
0 <= d <= 9
1 <= low <= high <= 2×10^8
Runtime: 4 ms
Memory Usage: 20.7 MB
1 class Solution { 2 func digitsCount(_ d: Int, _ low: Int, _ high: Int) -> Int { 3 let a:[Int] = f(high) 4 let b:[Int] = f(low - 1) 5 return a[d] - b[d] 6 } 7 8 func f(_ n:Int) -> [Int] 9 { 10 var dev:[Int] = [Int](repeating:0,count:10) 11 if n == 0 {return dev} 12 var i:Int = 1 13 while(i <= n) 14 { 15 let a:Int = (n/i)/10 16 for j in 0..<10 17 { 18 dev[j] += a*i 19 } 20 dev[0] -= i 21 for j in 0..<(n/i)%10 22 { 23 dev[j] += i 24 } 25 dev[(n/i)%10] += (n%i) + 1 26 i *= 10 27 } 28 return dev 29 } 30 }
- 上一篇 »JavaScript生成指定范围内的随机数
- 下一篇 »怎么用PHP查询指定日期范围内的数据?