Hexspeak in Python


Suppose a decimal number can be converted to its Hexspeak representation by converting it to an uppercase hexadecimal string at first, after that replacing all occurrences of the digit 0 with the letter O, and the digit 1 with the letter I.

This kind of representation is valid if and only if it consists only of the letters in the set {"A", "B", "C", "D", "E", "F", "I", "O"}.

So we have a string num representing a decimal integer N, we have to find the Hexspeak representation of N if it is correct, otherwise return "ERROR". So if num = “257”, then the output will be “IOI” as 257 is 101 in hexadecimal.

To solve this, we will follow these steps −

  • x := hex format of the digit
  • ans := an empty string
  • make one dictionary, and put the numbers (10 : ‘A’, 11 : ‘B’, 12 : ‘C’, 13 : ‘D’, 14 : ‘E’, 15 : ‘F’, 1 : ‘I’, 0 : ‘O’)
  • for each character i in x −
    • if i in d, then ans := ans + d[i], otherwise return “ERROR”
  • return ans

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def convertToHex(self, n):
      res = []
      while n > 0:
         res.append(n % 16)
         n //= 16
      return res[::-1]
   def toHexspeak(self, num):
      x = self.convertToHex(int(num))
      ans = ""
      d = {10:"A", 11:"B", 12:"C", 13:"D", 14:"E", 15:"F",0:"O",1:"I"}
      for i in x:
         if i in d:
            ans += d[i]
         else:
            return "ERROR"
      return ans
ob1 = Solution()
print(ob1.toHexspeak("659724"))

Input

"659724"

Output

"AIIOC"

Updated on: 28-Apr-2020

654 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements