[Swift]LeetCode1088. 易混淆數 II | Confusing Number II

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

We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid.git

confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.(Note that the rotated number can be greater than the original number.)github

Given a positive integer N, return the number of confusing numbers between 1 and N inclusive. 微信

Example 1:測試

Input: 20
Output: 6 Explanation: The confusing numbers are [6,9,10,16,18,19]. 6 converts to 9. 9 converts to 6. 10 converts to 01 which is just 1. 16 converts to 91. 18 converts to 81. 19 converts to 61. 

Example 2:spa

Input: 100
Output: 19 Explanation: The confusing numbers are [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100]. 

Note:code

  1. 1 <= N <= 10^9

本題咱們會將數字旋轉 180° 來生成一個新的數字。orm

好比 0、一、六、八、9 旋轉 180° 之後,咱們獲得的新數字分別爲 0、一、九、八、6。htm

二、三、四、五、7 旋轉 180° 後,是 沒法 獲得任何數字的。blog

易混淆數(Confusing Number)指的是一個數字在總體旋轉 180° 之後,可以獲得一個和原來 不一樣 的數,且新數字的每一位都應該是有效的。(請注意,旋轉後獲得的新數字可能大於原數字)

給出正整數 N,請你返回 1 到 N 之間易混淆數字的數量。 

示例 1:

輸入:20
輸出:6
解釋:
易混淆數爲 [6,9,10,16,18,19]。
6 轉換爲 9
9 轉換爲 6
10 轉換爲 01 也就是 1
16 轉換爲 91
18 轉換爲 81
19 轉換爲 61

示例 2:

輸入:100
輸出:19
解釋:
易混淆數爲 [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100]。 

提示:

  1. 1 <= N <= 10^9

3976 ms

 1 class Solution {
 2     var n:Int = 0
 3     var cands:[Int] = [0, 1, 6, 8, 9]
 4     var ans:Int = 0
 5     func confusingNumberII(_ N: Int) -> Int {
 6         self.n = N
 7         go(1, 0)
 8         if n == 1000000000
 9         {
10             ans += 1        
11         }
12         return ans
13     }
14     
15     func conv(_ d:Int) -> Int
16     {
17         if d == 6 {return 9}
18         else if d == 9 {return 6}
19         return d
20     }
21     
22     func rot(_ k:Int) -> Int
23     {
24         var k = k
25         var res:Int = 0
26         while(k > 0)
27         {
28             res = 10*res + conv(k%10)
29             k /= 10
30         }
31         return res
32     }
33     
34     func go(_ mul:Int,_ k:Int)
35     {
36         if k > n {return}
37         if mul == 1_000_000_000
38         {
39             if rot(k) != k {ans += 1}
40         }
41         else
42         {
43             for c in cands
44             {
45                 go(10*mul, k + mul*c)
46             }
47         }
48     }
49 }
相關文章
相關標籤/搜索