Hexspeak - Problem

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".

Input & Output

Example 1 — Valid Hexspeak
$ Input: num = "257"
Output: "IOI"
💡 Note: 257 in hex is 101. Replace '1'→'I' and '0'→'O' gives 'IOI'. All characters {I,O} are valid hexspeak.
Example 2 — Invalid Hexspeak
$ Input: num = "3"
Output: "ERROR"
💡 Note: 3 in hex is 3. The digit '3' cannot be converted to valid hexspeak (not in {A,B,C,D,E,F,I,O}).
Example 3 — Large Valid Number
$ Input: num = "171"
Output: "AB"
💡 Note: 171 in hex is AB. Both 'A' and 'B' are already valid hexspeak characters.

Constraints

  • 1 ≤ num ≤ 1012
  • num consists of only digits

Visualization

Tap to expand
Hexspeak - Single Pass Validation INPUT Decimal String: "257" Decimal Value: 257 Binary: 100000001 = 256 + 1 = 2^8 + 2^0 Valid Hexspeak Chars: A B C D E F I O Replace: '0' --> 'O' Replace: '1' --> 'I' ALGORITHM STEPS 1 Convert to Hex 257 --> "101" (hex) 257 = 0x101 = "101" 2 Replace '0' with 'O' "101" --> "1O1" 3 Replace '1' with 'I' "1O1" --> "IOI" 4 Validate Result Check all chars valid 'I' in valid set? OK 'O' in valid set? OK 'I' in valid set? OK All valid --> Return result FINAL RESULT Hexspeak Representation: "IOI" Character Breakdown: I O I from 1 from 0 from 1 Valid Hexspeak: OK Output: "IOI" Key Insight: Hexspeak converts numbers to readable letter combinations using hex digits A-F plus '0'-->'O' and '1'-->'I'. If any hex digit 2-9 remains after replacement, return "ERROR" since these can't become valid letters. TutorialsPoint - Hexspeak | Single Pass Validation Approach
Asked in
Amazon 15 Microsoft 8
12.0K Views
Medium Frequency
~15 min Avg. Time
380 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen