File: convert-a-number-to-hexadecimal/solution.py

Date: 2026-06-06

Time: 15:51

Purpose

This file solves LeetCode 405 — Convert a Number to Hexadecimal. It converts a 32-bit signed integer to its lowercase hexadecimal string representation, handling negative numbers via two's complement. The file is self-contained: solution and tests in one module.

Key Components

to_hex(num: int) -> str

Converts an integer in [-2^31, 2^31 - 1] to a hex string.

TestToHex

Eight test cases covering the boundary space: zero, small positives, powers of two, negative one (ffffffff), INTMAX (7fffffff), and INTMIN (80000000).

Patterns

Bit-manipulation hex conversion: Rather than using Python's built-in hex(), this manually extracts nibbles (4-bit groups) with bitwise AND and shift. This is the standard approach LeetCode expects — it demonstrates understanding of binary representation and two's complement.

Lookup string as digit map: hex_chars = "0123456789abcdef" uses string indexing as a lightweight alternative to a dictionary or conditional chain for digit-to-character conversion.

Reverse-accumulate: Building the result list in reverse (LSB first) then calling reversed() is a common idiom when extracting digits from least-significant to most-significant.

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The test_solution.py file in this same directory imports it. The massive "Imported By" list in the prompt is an artifact of the repo's test infrastructure, not actual imports of this module.

Flow


to_hex(-1)
  → num == 0? No
  → num &= 0xFFFFFFFF → 4294967295
  → loop: extract 0xF → 'f', shift right, repeat 8 times
  → result = ['f','f','f','f','f','f','f','f']
  → reversed → "ffffffff"

For positive 26:


  → 26 & 0xF = 10 → 'a', 26 >> 4 = 1
  → 1 & 0xF = 1 → '1', 1 >> 4 = 0
  → reversed(['a','1']) → "1a"

Invariants

Error Handling

None. The function trusts its caller to provide an integer in the valid range. No exceptions are raised or caught. Invalid input types would fail at the &= operation with a TypeError.

Topics to Explore

Beliefs