We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Convert a Number to Hexadecimal

Number: 405

Difficulty: Easy

Paid? No

Companies: Google, Meta, Adobe, Bloomberg, Amazon


Problem Description

Given a 32-bit integer num, return a string representing its hexadecimal representation. For negative numbers, the two’s complement method is used. The answer should contain lowercase letters only and no leading zeros (except for the number zero itself).


Key Insights

  • Use bit manipulation to extract hexadecimal digits (base 16) from the integer.
  • For negative numbers, apply the two’s complement representation by masking the number with 0xffffffff.
  • Convert the number by repeatedly taking the last 4 bits (using bitwise AND with 15) and mapping them to their corresponding hexadecimal character.
  • Handle the special case when num is 0 by returning "0".

Space and Time Complexity

Time Complexity: O(1) – The conversion processes at most 8 nibble-extractions for a 32-bit integer. Space Complexity: O(1) – Only a constant amount of extra space is used.


Solution

The solution uses a loop that repeatedly extracts the last 4 bits (a nibble) of the number by performing a bitwise AND with 15. Each nibble is then converted to its hexadecimal equivalent using a mapping string "0123456789abcdef". If the input number is negative, it is first transformed to its corresponding 32-bit two’s complement representation by performing an AND with 0xffffffff. This ensures that the algorithm works uniformly across positive and negative inputs. The hexadecimal digits are collected in reverse order, so they are reversed before returning the final result.


Code Solutions

# Define a function to convert a number to hexadecimal.
def toHex(num):
    # If the number is zero, return "0" immediately.
    if num == 0:
        return "0"
    
    # Mapping for hexadecimal characters.
    hex_chars = "0123456789abcdef"
    # For negative numbers, convert to 32-bit two's complement using bitwise AND.
    num &= 0xffffffff
    result = []
    
    # Extract hexadecimal digits until the number becomes 0.
    while num:
        # The nibble is the last 4 bits.
        digit = num & 15  # same as num % 16
        # Append the corresponding hexadecimal character.
        result.append(hex_chars[digit])
        # Shift right by 4 bits to process the next nibble.
        num >>= 4
    
    # Since the characters were collected in reverse order, reverse the list.
    return "".join(result[::-1])

# Example usage:
print(toHex(26))  # Output: "1a"
print(toHex(-1))  # Output: "ffffffff"
← Back to All Questions