Hexspeak

More downvotes.

For this problem, our first step is to convert the given decimal number into a hexadecimal representation. We then replace ‘0’ with ‘O’ and ‘1’ with ‘I’. If the resulting representation only consists of valid Hexspeak letters, we return it. Otherwise, we return “ERROR”.

Here’s a Python solution that follows this approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def toHexspeak(self, num: str) -> str:
        # Convert the number to uppercase hexadecimal
        hex_val = hex(int(num))[2:].upper()

        # Replace '0' with 'O' and '1' with 'I'
        hex_val = hex_val.replace('0', 'O').replace('1', 'I')

        # Check if the representation only consists of valid Hexspeak letters
        for letter in hex_val:
            if letter not in "ABCDEFIO":
                return "ERROR"

        # If all checks passed, return the Hexspeak representation
        return hex_val

This solution uses built-in functions to convert the string to an integer, the integer to hexadecimal, and the hexadecimal to uppercase. We then replace ‘0’s and ‘1’s with ‘O’ and ‘I’, respectively. The final step is to verify that the string only contains valid Hexspeak letters, returning “ERROR” if not.

The time complexity for this code is O(n), as we perform a constant amount of work for each character in the hexadecimal representation of the number. The space complexity is also O(n), as we store the hexadecimal representation in memory. Here, n refers to the number of digits in the hexadecimal representation.