为有牺牲多壮志,敢教日月换新天。

[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 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 

 

热烈欢迎,请直接点击!!!

 

进入博主App Store主页,下载使用各个作品!!!

 

注:博主将坚持每月上线一个新app!!!

 

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 digit d=1 occurs 6 times in 1,10,11,12,13. Note that the digit d=1 occurs twice in the number 11.

Example 2:

Input: d = 3, low = 100, high = 250
Output: 35
Explanation: 
The digit d=3 occurs 35 times in 103,113,123,130,131,...,238,239,243.

Note:

  1. 0 <= d <= 9
  2. 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=11,10,11,12,13 中出现 6 次。注意 d=1 在数字 11 中出现两次。

示例 2:

输入:d = 3, low = 100, high = 250
输出:35
解释:
数字 d=3103,113,123,130,131,...,238,239,243 出现 35 次。

提示:

  1. 0 <= d <= 9
  2. 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 }

 

posted @ 2019-06-02 00:36  为敢技术  阅读(834)  评论(0编辑  收藏  举报