Hexspeak Problem
Description
LeetCode Problem 1271.
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 <= num.length <= 12numdoes not contain leading zeros.- num represents an integer in the range
[1, 10^12].
Solution
Approach: Convert and Check
Do exactly what the statement says:
- Parse
numand write it in uppercase hexadecimal.numcan be up to10^12, which does not fit in a 32-bit integer, so parse it as a 64-bit integer (long/long long). - Replace every
0withOand every1withI. - The other letters
AtoFare already allowed, so the representation is valid unless a digit from2to9is left. If one is, return"ERROR"; otherwise return the string.
For example, 257 is 101 in hexadecimal, which becomes "IOI", while 3 stays 3 and gives "ERROR".
Complexity: O(log n) time and space for the number n: its hexadecimal form has at most 10 digits here.
class Solution:
def toHexspeak(self, num: str) -> str:
hexspeak = hex(int(num))[2:].upper().replace('0', 'O').replace('1', 'I')
# after the replacement, any digit left is one of 2..9
if any(c.isdigit() for c in hexspeak):
return "ERROR"
return hexspeak