#405

Convert a Number to Hexadecimal

Easy
MathStringBit ManipulationBit ManipulationString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution efficiently converts the number to hexadecimal using bit manipulation. By using bitwise operations, we can directly extract the hexadecimal digits without needing to perform division repeatedly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a string array to hold hexadecimal characters.
  2. 2Step 2: If the number is negative, adjust it using two's complement.
  3. 3Step 3: Use a loop to extract each hexadecimal digit using bitwise AND and right shift operations.
  4. 4Step 4: Assemble the digits into a string and return it, ensuring no leading zeros.
solution.py10 lines
1# Full working Python code
2
3def toHex(num):
4    if num < 0:
5        num += 2**32
6    hex_chars = '0123456789abcdef'
7    hex_string = ''
8    for i in range(8):
9        hex_string = hex_chars[(num >> (4 * (7 - i))) & 0xf] + hex_string
10    return hex_string.lstrip('0') or '0'

Complexity note: The time complexity is O(1) because we are always processing a fixed number of bits (32 bits for a 32-bit integer), and the space complexity is also O(1) as we are not using any additional data structures that grow with input size.

  • 1Understanding two's complement is crucial for handling negative numbers.
  • 2Bitwise operations can significantly optimize performance when converting between number bases.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.