HomeLeetcode405. Convert a Number to Hexadecimal - Leetcode Solutions

405. Convert a Number to Hexadecimal – Leetcode Solutions

Description

Given a 32-bit integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

Examples:

Example 1:

Input: num = 26
Output: "1a"

Example 2:

Input: num = -1
Output: "ffffffff"

Solution in Python

Key Concepts:

  1. Two’s Complement:
    • For negative numbers, two’s complement is used to represent them in binary. This means adding 232 to the number for the 32-bit range.
  2. Hexadecimal Conversion:
    • Hexadecimal uses base 16, represented by digits 0-9 and letters a-f.
    • For each 4 bits in binary, there is one corresponding hexadecimal digit.
  3. Iterative Approach:
    • Extract the last 4 bits (using bitwise AND with 0b1111 or 15), convert them to a hexadecimal digit, and then right-shift the number by 4 bits.
    • Continue until the number becomes 0 or all 32 bits are processed.
  4. Edge Case:
    • For the number 0, directly return "0".
Python
class Solution:
    def toHex(self, num: int) -> str:
        # Handle the special case where the number is 0
        if num == 0:
            return "0"
        
        # Hexadecimal characters
        hex_chars = "0123456789abcdef"
        
        # If the number is negative, apply two's complement for 32-bit numbers
        if num < 0:
            num += 2 ** 32
        
        # Initialize an empty result string
        result = []
        
        # Extract hexadecimal digits one by one
        while num > 0:
            # Get the last 4 bits (a single hex digit)
            digit = num & 15  # Equivalent to num % 16
            result.append(hex_chars[digit])
            # Right shift the number by 4 bits
            num >>= 4
        
        # The digits are generated in reverse order, so reverse the result and join
        return ''.join(reversed(result))

Explanation of Code:

  1. Handle Zero:
    • If num == 0, we immediately return "0" since it has no hexadecimal representation other than itself.
  2. Two’s Complement for Negative Numbers:
    • For negative numbers, we add 232 to bring them into the range of non-negative 32-bit integers.
  3. Extract Hexadecimal Digits:
    • Use num & 15 to get the last 4 bits, which correspond to a single hexadecimal digit.
    • Append the corresponding character from hex_chars to the result.
  4. Right Shift:
    • Shift the number 4 bits to the right to process the next set of bits.
  5. Reverse the Result:
    • Since we generate hexadecimal digits starting from the least significant, we reverse the result list before joining and returning it.

Solution in C++

C++
class Solution {
public:
    string toHex(int num) {
        // If the number is 0, directly return "0".
        if (num == 0) return "0";

        // Array of characters to represent hexadecimal digits.
        const char hexDigits[] = "0123456789abcdef";

        // Since an integer is 32 bits, the result can have at most 8 hex digits.
        string result;

        // Loop up to 8 times (4 bits per hex digit for 32-bit numbers).
        for (int i = 0; i < 8 && num != 0; ++i) {
            // Extract the last 4 bits of the number and convert them to hex.
            result = hexDigits[num & 0xf] + result;

            // Perform a logical right shift by 4 bits.
            // For negative numbers, in two's complement representation, this will shift appropriately.
            num >>= 4;
        }

        // Return the resulting string.
        return result;
    }
};

Solution in Javascript

JavaScript
var toHex = function(num) {
    // Handle the case when the input number is 0
    if (num === 0) {
        return "0";
    }

    // Define a map for hexadecimal characters
    // For digits 0-15, map to corresponding hexadecimal symbols
    const hexMap = "0123456789abcdef";

    // Use an unsigned 32-bit mask to handle negative numbers (two's complement)
    // If the number is negative, convert it to its 32-bit unsigned equivalent
    num = num >>> 0;

    // Initialize an empty string to store the hexadecimal result
    let hexString = "";

    // Continue dividing the number by 16 and converting the remainder
    // to the corresponding hexadecimal digit until the number becomes 0
    while (num > 0) {
        // Get the remainder when divided by 16 (the current hexadecimal digit)
        const remainder = num % 16;

        // Prepend the corresponding hex character to the result string
        hexString = hexMap[remainder] + hexString;

        // Perform integer division by 16 (shift right by 4 bits)
        num = Math.floor(num / 16);
    }

    // Return the resulting hexadecimal string
    return hexString;
};

Solution in Java

Java
class Solution {
    public String toHex(int num) {
        // Handle the edge case when the input number is 0
        if (num == 0) {
            return "0";
        }

        // Initialize the hexadecimal character set
        char[] hexChars = "0123456789abcdef".toCharArray();

        // The result string to hold the hexadecimal representation
        StringBuilder hexString = new StringBuilder();

        // Process each of the 8 hexadecimal digits (4 bits at a time)
        for (int i = 0; i < 8 && num != 0; i++) {
            // Extract the last 4 bits of the number
            int currentNibble = num & 0xf;

            // Convert the 4-bit value to a hexadecimal character and append it
            hexString.append(hexChars[currentNibble]);

            // Perform a logical right shift by 4 bits
            num >>>= 4;
        }

        // The StringBuilder contains the hexadecimal digits in reverse order
        // Reverse it to get the correct hexadecimal representation
        return hexString.reverse().toString();
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular