zoukankan      html  css  js  c++  java
  • 【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 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
            
  • 相关阅读:
    创建的第二个随笔
    Jq基础简介
    从VG中去除PV unknown device
    redhat using publicyum
    Oracle 11g 安装文件说明
    WP8教程: 第一个WP8应用(一)
    WP8教程: 第一个WP8应用(二)
    sqlplus 的登录方式
    redhat7 安装oracle11g 缺少pdksh包
    jquery实现一个substr截取字符串的小效果
  • 原文地址:https://www.cnblogs.com/seyjs/p/11967411.html
Copyright © 2011-2022 走看看