A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
Example 1:
Input: "69"
Output: true
Example 2:
Input: "88"
Output: true
Example 3:
Input: "962"
Output: false
- 根据题目要求,
num
中所有数字必须为0、1、6、8、9
,才有可能是一个strobogrammatic number
。 - 这几个数字对应
0, 1, 9, 8, 6
, 倒序遍历num
,看组成的数字是否与原num
相等即可。
class Solution:
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
d = {"0": "0", "1": "1", "6": "9", "8": "8", "9": "6"}
strobogrammatic = ""
for i in num[::-1]:
if i in d:
strobogrammatic += d[i]
else:
return False
return strobogrammatic == num