Similar Problems

Similar Problems not available

Hexspeak - Leetcode Solution

Companies:

LeetCode:  Hexspeak Leetcode Solution

Difficulty: Easy

Topics: math string  

Hexspeak is a problem on LeetCode that requires you to convert a given integer into a string that represents the hexadecimal value of the integer. In addition, any digit that has a value greater than or equal to 10 must be replaced with a corresponding English letter using the Hexspeak alphabet "O, I, E, A, S, G, T, B". If the integer contains any digit that cannot be represented by this alphabet, the function should return "ERROR".

Here's an example solution in Python:

def toHexspeak(num: str) -> str:
    hex_str = hex(int(num))[2:].upper()  # convert to hexadecimal
    hexspeak_chars = {
        '0': 'O',
        '1': 'I',
        '2': 'E',
        '3': 'A',
        '4': 'S',
        '5': 'G',
        '6': 'T',
        '7': 'B',
        '8': 'ERROR',
        '9': 'ERROR',
        'A': 'A',
        'B': 'B',
        'C': 'ERROR',
        'D': 'ERROR',
        'E': 'E',
        'F': 'F'
    }
    hexspeak = ''
    for char in hex_str:
        if char not in hexspeak_chars:
            return 'ERROR'
        hexspeak += hexspeak_chars[char]
    return hexspeak

The function takes in an argument num, which is the integer to convert to Hexspeak. First, the function uses the built-in hex function to convert the integer to hexadecimal, and then extracts the hexadecimal value as a string.

Next, the function defines a dictionary that maps each hexadecimal digit to its corresponding Hexspeak alphabet character. It then loops through each digit in the hexadecimal string and looks up the corresponding alphabet character in the dictionary. If the digit is not a valid Hexspeak character (i.e. it is 8 or 9), the function returns "ERROR". Otherwise, it adds the Hexspeak character to a new string, which is ultimately returned as the result.

Here are some example inputs and expected outputs:

>>> toHexspeak('257')
'IOI'
>>> toHexspeak('3E8')
'SOT'
>>> toHexspeak('64')
'ERROR'
>>> toHexspeak('10000')
'ERROR'

Hexspeak Solution Code

1