Skip to main content

405. Convert a Number to Hexadecimal

easy

Convert an integer to its hexadecimal string using two's complement for negatives. Mask 4 bits at a time and map each nibble to a hex digit.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an 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.

Constraints

  • -2^31 <= num <= 2^31 - 1

Examples

Example 1

Input
num = 26
Output
"1a"

Example 2

Input
num = -1
Output
"ffffffff"

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Treat num as an unsigned 32-bit value. In Python, mask with 0xFFFFFFFF to coerce to the bit pattern. In Java/Go, the right-shift operator >>> already does unsigned shifts.

Hint 2

Extract one hex digit at a time using num & 0xF (the low 4 bits), then right-shift by 4. Use a lookup table '0123456789abcdef'.

Hint 3

Special-case num == 0 → return "0". Otherwise loop while the working value is nonzero, prepending digits.

Solution approach

Reveal approach

Nibble extraction with unsigned-shift semantics. If num == 0, return "0". Otherwise treat num as a 32-bit unsigned bit-pattern (in Python mask with 0xFFFFFFFF; in Java use >>>; in C++ cast to uint32_t). Loop while the working value is nonzero: digit = value & 0xF; result_chars.push(hex_digits[digit]); value = value >>> 4 (unsigned right shift by 4). After the loop, reverse the collected digits and join into a string. O(8) ≈ O(1) iterations because a 32-bit value has at most 8 hex digits. O(1) space. The unsigned-shift detail is what makes negatives work: in two's complement, -1 has all 32 bits set, which gives 'ffffffff'.

Complexity

Time
O(1)
Space
O(1)

Related patterns

  • bit-manipulation

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Facebook

Practice these live with InterviewChamp.AI

Drill Convert a Number to Hexadecimal and Bit Manipulation problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →