Convert a Number to Hexadecimal - Problem
Given a 32-bit signed integer num, your task is to convert it into its hexadecimal representation as a string.
๐ฏ Key Requirements:
- For negative integers, use the two's complement method
- All letters in the result must be lowercase (a-f)
- No leading zeros except when the number itself is zero
- No built-in conversion functions allowed!
Examples:
26 โ "1a"(26 = 1ร16ยน + 10ร16โฐ)-1 โ "ffffffff"(32-bit two's complement)0 โ "0"(special case)
This problem tests your understanding of number systems, bit manipulation, and two's complement representation.
Input & Output
example_1.py โ Basic Positive Number
$
Input:
num = 26
โบ
Output:
"1a"
๐ก Note:
26 in binary is 11010. Grouping 4 bits from right: 1010 (10 โ 'a'), 0001 (1 โ '1'). Reading left to right gives '1a'.
example_2.py โ Negative Number
$
Input:
num = -1
โบ
Output:
"ffffffff"
๐ก Note:
-1 in 32-bit two's complement is all 1s (11111111111111111111111111111111). Each group of 4 ones (1111) converts to 'f', giving 8 'f's total.
example_3.py โ Zero Edge Case
$
Input:
num = 0
โบ
Output:
"0"
๐ก Note:
Zero is a special case that should return '0' directly, not an empty string.
Visualization
Tap to expand
Understanding the Visualization
1
Understand the mapping
Each hex digit represents exactly 4 bits (0000-1111 maps to 0-f)
2
Extract bit groups
Use bitwise AND with 0xf to extract the rightmost 4 bits
3
Convert to hex
Map the 4-bit value (0-15) to corresponding hex character
4
Shift and repeat
Right-shift by 4 bits and repeat until no significant bits remain
5
Handle two's complement
Negative numbers naturally work due to their bit representation
Key Takeaway
๐ฏ Key Insight: Each hexadecimal digit represents exactly 4 bits, allowing direct conversion through bitwise operations without division.
Time & Space Complexity
Time Complexity
O(1)
Fixed number of iterations (at most 8) regardless of input size, since we're dealing with 32-bit integers
โ Linear Growth
Space Complexity
O(1)
Result string length is bounded by 8 characters for 32-bit integers, so space is constant
โ Linear Space
Constraints
- -231 โค num โค 231 - 1
- No built-in conversion functions allowed
- Result must use lowercase letters (a-f)
- No leading zeros except for the number 0 itself
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code