[Swift]LeetCode1067. 範圍內的數字計數 | Digit Count in Range

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-rvxksbkn-mb.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 
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.git

Example 1:github

Input: d = 1, low = 1, high = 13 Output: 6 Explanation: The digit  occurs  times in . Note that the digit  occurs twice in the number . d=161,10,11,12,13d=111

Example 2:微信

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

Note:app

  1. 0 <= d <= 9
  2. 1 <= low <= high <= 2×10^8 

給定一個在 0 到 9 之間的整數 d,和兩個正整數 low 和 high 分別做爲上下界。返回 d 在 low 和 high 之間的整數中出現的次數,包括邊界 low 和 highspa

示例 1:code

輸入:d = 1, low = 1, high = 13
輸出:6
解釋: 
數字  在 。注意  在數字 11 中出現兩次。
d=11,10,11,12,13 中出現 6 次d=1

示例 2:orm

輸入:d = 3, low = 100, high = 250
輸出:35
解釋:
數字  在 d=3103,113,123,130,131,...,238,239,243 出現 35 次。

提示:htm

  1. 0 <= d <= 9
  2. 1 <= low <= high <= 2×10^8

Runtime: 4 msblog

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 }
相關文章
相關標籤/搜索