题目如下:

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 letter O, and the digit 1 with the letter I.  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 integer N, return the Hexspeak representation of N 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
        

 

相关文章:

  • 2022-02-17
  • 2021-08-08
  • 2021-06-24
  • 2022-12-23
  • 2021-12-07
  • 2021-05-20
  • 2022-12-23
  • 2021-03-31
猜你喜欢
  • 2021-06-07
  • 2022-12-23
  • 2021-10-16
  • 2021-10-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-30
相关资源
相似解决方案