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

# 1271. Hexspeak

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;
}
}