Convert a Number to Hexadecimal - Problem

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.

Input & Output

Example 1 — Positive Number
$ Input: num = 26
Output: 1a
💡 Note: 26 in binary is 11010. Extract 4 bits: 1010 (10 in decimal) = 'a', then 0001 (1 in decimal) = '1'. Result: '1a'
Example 2 — Negative Number
$ Input: num = -1
Output: ffffffff
💡 Note: -1 in two's complement (32-bit) is all 1s: 11111111111111111111111111111111. Each group of 4 ones = 15 = 'f'. Result: 'ffffffff'
Example 3 — Zero
$ Input: num = 0
Output: 0
💡 Note: Special case: 0 should return '0' directly, not an empty string

Constraints

  • -231 ≤ num ≤ 231 - 1

Visualization

Tap to expand
Convert Number to Hexadecimal26(Decimal)Input NumberConvert to Base 1626 ÷ 16 = 1 remainder 1010 in hex = a1 ÷ 16 = 0 remainder 1Conversion Process1a(Hex)Output String-1Two\'s ComplementffffffffHandles positive and negative integers using two\'s complement
Understanding the Visualization
1
Input
32-bit integer (positive or negative)
2
Process
Convert to hex using division or bit manipulation
3
Output
Hexadecimal string with lowercase letters
Key Takeaway
🎯 Key Insight: Each hex digit represents exactly 4 bits, making bit manipulation the most efficient approach
Asked in
Microsoft 15 Apple 8
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen