1. Built-In Function

class Solution:
    def toHexspeak(self, num: str) -> str:
        res = []
        for c in format(int(num), "X"):
            if c == "0":
                res.append("O")
            elif c == "1":
                res.append("I")
            elif c.isdigit():
                return "ERROR"
            else:
                res.append(c)
        return "".join(res)

Time & Space Complexity

  • Time complexity: O(log⁡n)O(\log n)
  • Space complexity: O(log⁡n)O(\log n)

Where nn is the integer value of numnum.


2. Math (Repeated Division)

class Solution:
    def toHexspeak(self, num: str) -> str:
        n = int(num)
        res = []
        while n > 0:
            d = n % 16
            if d == 0:
                res.append("O")
            elif d == 1:
                res.append("I")
            elif d >= 10:
                res.append(chr(ord("A") + d - 10))
            else:
                return "ERROR"
            n //= 16
        return "".join(reversed(res))

Time & Space Complexity

  • Time complexity: O(log⁡n)O(\log n)
  • Space complexity: O(log⁡n)O(\log n)

Where nn is the integer value of numnum.


3. Bit Manipulation

class Solution:
    def toHexspeak(self, num: str) -> str:
        n = int(num)
        res = []
        while n > 0:
            d = n & 15
            if d == 0:
                res.append("O")
            elif d == 1:
                res.append("I")
            elif d >= 10:
                res.append(chr(ord("A") + d - 10))
            else:
                return "ERROR"
            n >>= 4
        return "".join(reversed(res))

Time & Space Complexity

  • Time complexity: O(log⁡n)O(\log n)
  • Space complexity: O(log⁡n)O(\log n)

Where nn is the integer value of numnum.