← Questions

Convert an integer to hexadecimal

0
MetaCodingLast asked Dec 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Dec 2025. It tests bit manipulation and math.

Given a 32-bit signed integer, return its hexadecimal representation as a string. Use lowercase a–f and no leading zeros (zero itself is "0"). A negative number is written as its 32-bit two's-complement value. Do not use built-in base conversion such as hex(), format() or toString(16).

Interface

Unless you agree on a different interface with the interviewer, assume:

  • to_hex(num: int) -> str.

Example

26            ->  "1a"         # 1 * 16 + 10
0             ->  "0"
255           ->  "ff"
-1            ->  "ffffffff"   # every bit set
-2147483648   ->  "80000000"
2147483647    ->  "7fffffff"

Constraints

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

Clarifying questions

  • Lowercase or uppercase letters?
  • Should the result have a 0x prefix?
  • How should negative numbers be shown: two's complement or a minus sign?

What a strong answer covers

  • Handle 0 up front, or the loop produces an empty string.
  • For negatives, convert to the unsigned 32-bit value (num + 2^32, or num & 0xFFFFFFFF). In languages with fixed 32-bit integers, use an unsigned shift instead.
  • Take the low 4 bits (num & 0xF), map them through "0123456789abcdef", shift right by 4, and repeat at most 8 times.
  • Build the digits from least significant to most significant, then reverse.
  • Why an arithmetic right shift on a negative number never reaches 0 in some languages, and how the 8-digit limit or an unsigned shift avoids that.
  • O(1) time (at most 8 digits).
  • Tests: 0, small positives, -1, the minimum and maximum 32-bit values, powers of 16.

Follow-ups

  • Convert to any base from 2 to 36, with negatives shown with a minus sign.
  • Parse a hexadecimal string back into a signed 32-bit integer.
  • Do the same for 64-bit integers.

Where it's asked

  • Meta · AI-enabled coding · Last asked Dec 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

bit manipulation · math

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding