Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1271.html

1271. Hexspeak

Level

Easy

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 <= N <= 10^12
  • There are no leading zeros in the given string.
  • All answers must be in uppercase letters.

Solution

The solution is quite straightforward. Convert the decimal number to the hexadecimal string, change the string to uppercase, and replace 0 with O and 1 with I. Then check each character in the string. If a character out of the set {"A", "B", "C", "D", "E", "F", "I", "O"} occurs, return "ERROR". If the string is valid, return the string.

  • class Solution {
        public String toHexspeak(String num) {
            long decimal = Long.parseLong(num);
            String hex = toHex(decimal);
            hex = hex.toUpperCase();
            hex = hex.replaceAll("0", "O");
            hex = hex.replaceAll("1", "I");
            String validStr = "ABCDEFIO";
            char[] hexArray = hex.toCharArray();
            for (char c : hexArray) {
                if (validStr.indexOf(c) < 0)
                    return "ERROR";
            }
            return hex;
        }
    
        public String toHex(long num) {
            String hex = "";
            while (num > 0) {
                int remainder = (int) (num % 16);
                String digit = remainder < 10 ? String.valueOf(remainder) : String.valueOf((char) ('A' + (remainder - 10)));
                hex = digit + hex;
                num /= 16;
            }
            return hex;
        }
    }
    
  • // OJ: https://leetcode.com/problems/hexspeak/
    // Time: O(N)
    // Space: O(N)
    class Solution {
    public:
        string toHexspeak(string n) {
            stringstream ss;
            ss << uppercase << hex << stoll(n);
            string ans = ss.str();
            for (char &c : ans) {
                if (c == '0') c = 'O';
                else if (c == '1') c = 'I';
                else if (isdigit(c)) return "ERROR";
            }
            return ans;
        }
    };
    
  • 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'
    
    
    

All Problems

All Solutions