Skip to content
Problem 405 · LeetCode 405(opens in a new tab)

Convert a Number to Hexadecimal

EasyBit manipulation

You get a 32-bit signed integer num. Return it written in base 16 as a string, using the digits 0 to 9 and the lowercase letters a to f.

A negative number is written as its 32-bit two's complement pattern, so -1 becomes eight f characters. The answer has no leading zeros, except that 0 itself is "0". Do not use a built-in conversion.

Example 1

Input:  num = 2024
Output: "7e8"
Why:    7 · 256 + 14 · 16 + 8 = 2024
2 more examples and the constraints

Example 2

Input:  num = -16
Output: "fffffff0"
Why:    the 32-bit pattern of -16 is 2³² − 16

Example 3

Input:  num = 0
Output: "0"
Why:    zero is the one answer that is a single 0

Constraints

  • −2,147,483,648 ≤ num ≤ 2,147,483,647
  • The answer has between 1 and 8 characters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Divide by 16O(1)
  2. Mask and shiftO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 32-bit numberVerdict
Divide by 16O(1)
Passes; negatives need a fix
Mask and shiftO(1)
Best; negatives come for free

Both do at most 8 rounds; the mask version uses cheap bit operations and no wider type.

Edge cases to test

  • Zero. Must return "0", not the empty string.
  • Minus one. -1 is all 32 bits set: "ffffffff".
  • Smallest int. −2,147,483,648 is "80000000"; negating it overflows, so never flip the sign.
  • Zeros inside. 4096 is "1000": inner zeros stay, only leading ones are dropped.

Common mistakes

  • Using a signed right shift, which never reaches 0 for a negative number.
  • Returning "" for 0 because the loop body never runs.
  • Writing "-10" for −16 instead of its two's complement pattern.

How to talk through it

  1. 1Clarify. Negatives as 32-bit two's complement? Lowercase letters? Is 0 written as "0"?
  2. 2Give the division method. Remainders mod 16 give the digits; negatives need 2³² added first.
  3. 3Switch to bits. One hex digit is 4 bits: & 15 to read, shift by 4 to drop.
  4. 4Code it unsigned. Use the unsigned shift and a do-while so 0 still gives one digit.
  5. 5Test out loud. Run 0, -1 and the smallest int before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?