LeetCode 1271: Hexspeak Solution

Master LeetCode problem 1271 (Hexspeak), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1271. Hexspeak

Problem Explanation

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.

: :

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1271 (Hexspeak)?

This page provides optimized solutions for LeetCode problem 1271 (Hexspeak) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1271 (Hexspeak)?

The time complexity for LeetCode 1271 (Hexspeak) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1271 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1271 in Java, C++, or Python.

Back to LeetCode Solutions