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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code