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 Hexadecimal INPUT 32-bit Integer num = 26 (decimal) Binary Form: 00000000000000000000000000011010 4-bit Groups (from right): 1010 = 10 0001 = 1 0000 ... Hex: 0-9, a-f (10-15) 10 = 'a', 1 = '1' No built-in methods! ALGORITHM STEPS 1 Handle Edge Cases If num=0, return "0" 2 Handle Negative (2's comp) num += 2^32 if negative 3 Extract 4 bits at a time digit = num AND 15 (0xF) 4 Convert to hex char Map: 0-9 or a-f Iteration Process: Step num num&15 hex 1 26 10 'a' 2 1 1 '1' 3 0 stop -- num = num >> 4 (shift right) Reverse result: "a" + "1" --> "1a" FINAL RESULT Hexadecimal Output "1a" Verification: 1 x 16^1 = 16 a(10) x 16^0 = 10 Total = 26 OK Complexity Time: O(1) Space: O(1) No leading zeros All lowercase letters 32-bit constraint handled Key Insight: Use bitwise AND with 15 (0xF) to extract the last 4 bits, which maps directly to one hex digit. Right-shift by 4 bits to process next hex digit. For negative numbers, add 2^32 to convert to unsigned representation (two's complement). Build result in reverse order, then reverse at end. TutorialsPoint - Convert a Number to Hexadecimal | Optimal Bit Manipulation 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