LeetCode 1271. Hexspeak Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1271. Hexspeak

Description

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 <= 12
  • num does not contain leading zeros.
  • num represents an integer in the range [1, 1012].

Solutions

Solution 1: Simulation

Convert the number to a hexadecimal string, then traverse the string, convert the number 0 to the letter O, and the number 1 to the letter I. Finally, check whether the converted string is valid.

The time complexity is O(log n), where n is the size of the decimal number represented by num.

PythonJavaC++Go
class Solution: def toHexspeak 🔒(self, num: str) -> str: s = set('ABCDEFIO') t = hex(int(num))[2:].upper().replace('0', 'O').replace('1', 'I') return t if all(c in s for c in t) else 'ERROR'(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !