leetcode1271. Hexspeak
Posted seyjs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1271. 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
以上是关于leetcode1271. Hexspeak的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-第14周双周赛-1271-十六进制魔术数字
LeetCode-面试算法经典-Java实现106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)(示例(代码片