LeetCode 1271: Hexspeak

MathString

Problem Description

Explanation:

To solve this problem, we need to convert a given non-negative integer to a string in the hexadecimal representation. The resulting string should only contain the characters 'A', 'B', 'C', 'D', 'E', 'F', and 'I' when written in uppercase. If any other characters are present in the string, we should return "ERROR".

The approach is to convert the given integer to a hexadecimal string using the built-in functions of the respective programming languages. After converting, we iterate through the characters of the hexadecimal string to check if any character other than 'A', 'B', 'C', 'D', 'E', 'F', or 'I' is present. If found, we return "ERROR"; otherwise, we return the uppercase hexadecimal string.

: :

Solutions

class Solution {
    public String toHexspeak(String num) {
        long n = Long.parseLong(num);
        String hexString = Long.toHexString(n).toUpperCase();
        StringBuilder result = new StringBuilder();
        
        for (char c : hexString.toCharArray()) {
            if (c == '0') {
                result.append('O');
            } else if (c == '1') {
                result.append('I');
            } else if (c >= '2' && c <= '9') {
                result.append('E');
            } else {
                result.append(c);
            }
        }
        
        if (result.toString().matches(".*[2-9].*")) {
            return "ERROR";
        }
        
        return result.toString();
    }
}

Loading editor...