LeetCode 405: Convert a Number to Hexadecimal Solution

Master LeetCode problem 405 (Convert a Number to Hexadecimal), 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.

405. Convert a Number to Hexadecimal

Problem Explanation

Explanation

To convert a given integer to its hexadecimal representation, we can use bitwise operations to extract 4 bits at a time from the integer and map them to the corresponding hexadecimal digit. We can repeatedly divide the integer by 16 (since hexadecimal is base 16) to get the corresponding hexadecimal representation.

  1. Initialize a mapping of decimal values to their corresponding hexadecimal characters.
  2. Handle negative numbers by first converting them to positive numbers using two's complement method.
  3. Use bitwise operations to extract 4 bits at a time and map them to the hexadecimal character.
  4. Continue this process until the integer becomes 0.
  5. Reverse the resulting hexadecimal string to get the correct representation.

Time Complexity: O(log(n)) where n is the value of the input integer. Space Complexity: O(1)

Solution Code

class Solution {
    public String toHex(int num) {
        if (num == 0) return "0";
        
        char[] hexChars = "0123456789abcdef".toCharArray();
        StringBuilder sb = new StringBuilder();
        
        while (num != 0) {
            sb.append(hexChars[num & 0xf]);
            num >>>= 4;
        }
        
        return sb.reverse().toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 405 (Convert a Number to Hexadecimal)?

This page provides optimized solutions for LeetCode problem 405 (Convert a Number to Hexadecimal) 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 405 (Convert a Number to Hexadecimal)?

The time complexity for LeetCode 405 (Convert a Number to Hexadecimal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 405 on DevExCode?

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

Back to LeetCode Solutions