码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1271. Hexspeak

时间:2019-12-03 19:50:45      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:ted   sel   ali   uppercase   int   first   inpu   color   leading   

题目如下:

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
        

 

【leetcode】1271. Hexspeak

标签:ted   sel   ali   uppercase   int   first   inpu   color   leading   

原文地址:https://www.cnblogs.com/seyjs/p/11967411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!