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.

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

Visualization

Tap to expand
Binary to Hexadecimal ConversionNumber: 26 (decimal)Binary: 00000000000000000000000000011010Group into 4-bit chunks (right to left):0000 0000 0000 0000 0000 0000 0001 101010100001Convert each 4-bit group to hex:1010โ‚‚= 10โ‚โ‚€ = 'a'0001โ‚‚= 1โ‚โ‚€ = '1'Conversion Table0000โ†’0 0001โ†’1 0010โ†’2 0011โ†’30100โ†’4 0101โ†’5 0110โ†’6 0111โ†’71000โ†’8 1001โ†’9 1010โ†’a 1011โ†’b1100โ†’c 1101โ†’d 1110โ†’e 1111โ†’fFinal ResultReading from left to right: '1' + 'a' = "1a"26โ‚โ‚€ = "1a"โ‚โ‚†
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.
Asked in
Microsoft 15 Amazon 12 Google 8 Apple 6
32.0K Views
Medium Frequency
~15 min Avg. Time
1.4K 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