[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 = 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 }

 

转载于:https://www.cnblogs.com/strengthen/p/10961687.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值