【leetcode】1271. Hexspeak
题目如下:
A decimal number can be converted to its Hexspeak representation by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit
0
with the letterO
, and the digit1
with the letterI
. Such a representation is valid if and only if it consists only of the letters in the set{"A", "B", "C", "D", "E", "F", "I", "O"}
.Given a string
num
representing a decimal integerN
, return the Hexspeak representation ofN
if it is valid, otherwise return"ERROR"
.Example 1:
Input: num = "257" Output: "IOI" Explanation: 257 is 101 in hexadecimal.Example 2:
Input: num = "3" Output: "ERROR"Constraints:
1 <= N <= 10^12
- There are no leading zeros in the given string.
- All answers must be in uppercase letters.
解题思路:转成十六进制后,把0/1分别替换成O/I,然后检查字符串中是否包含 "A", "B", "C", "D", "E", "F", "I", "O" 以外的字符。
代码如下:
class Solution(object): def toHexspeak(self, num): """ :type num: str :rtype: str """ num = hex(int(num))[2:] num = num.upper() num = num.replace('0','O') num = num.replace('1', 'I') valid = ["A", "B", "C", "D", "E", "F", "I", "O"] for i in num: if i not in valid:return "ERROR" return num