【LeetCode】788. Rotated Digits 解題報告(Python)
目錄
題目描述
X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number.
Now given a positive number N, how many numbers X from 1 to N are good?
Example:
Input: 10
Output: 4
Explanation:
There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
Note:
- N will be in range [1, 10000].
題目大意
在[1,N]雙閉區間中,有多少個數字,將其倒影之後和自身不同。
解題方法
重要的是理解題意,就好比下面的這個倒影,要求倒影和自身不同,但倒影也必須是數字:
可以總結出以下的要求:
- 該數字中不含
[3, 4, 7]
,否則其倒影不是數字。 - 該數字中必須包含
[2, 5, 6, 9]
中的至少一個,否則倒影和原數字相同
最後的結果是有多少個,遍歷之後很容易得到答案。
class Solution(object):
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
"""
valid = [2, 5, 6, 9]
nonValid = [3, 4, 7]
def isGood(num):
for y in nonValid:
if str(y) in str(num):
return False
return any(str(x) in str(num) for x in valid)
return sum(map(int, [isGood(n) for n in range(1, N + 1)]))
二刷,基於同樣的思想,寫了一個更簡潔的程式碼。
class Solution(object):
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
"""
dmap = {"0" : "0", "1" : "1", "8" : "8", "2" : "5", "5" : "2", "6" : "9", "9" : "6"}
res = 0
for num in range(1, N + 1):
numlist = list(str(num))
if any(x in numlist for x in ["3", "4", "7"]):
continue
numRotate = map(lambda x : dmap[x], numlist)
if numRotate == numlist:
continue
res += 1
return res
看了別人的提交,發現了一個更簡單的思路,就是我們不需要把翻轉後的數字構建出來,我們只需要找出特定的字元是否在字串中即可。比如,如果數字包含["3", "4", "7"]
,那麼肯定不可以。如果數字包含["2", "5", "6", "9"]
,那麼一定可以。如果這些數字都不包含,那麼就是翻轉之後是自身的數字,就不能計算到結果裡。
class Solution(object):
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
"""
dmap = {"0" : "0", "1" : "1", "8" : "8", "2" : "5", "5" : "2", "6" : "9", "9" : "6"}
res = 0
for num in range(1, N + 1):
if any(x in str(num) for x in ["3", "4", "7"]):
continue
if any(x in str(num) for x in ["2", "5", "6", "9"]):
res += 1
return res
日期
2018 年 2 月 26 日
2018 年 11 月 11 日 —— 剁手節快樂