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.