Convert 32-bit integer to hexadecimal
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of integer representation, hexadecimal notation, bitwise operations, and 32-bit two's complement arithmetic. It is commonly asked to assess low-level data representation and edge-case handling within the Coding & Algorithms domain, and it tests practical implementation skills alongside conceptual understanding of binary and base conversion.
Constraints
- -2^31 <= num <= 2^31 - 1
- Output uses lowercase letters a-f.
- No leading zeros, except num = 0 which returns "0".
- Negative numbers use 32-bit two's complement representation.
Examples
Input: (26,)
Expected Output: "1a"
Explanation: 26 = 0x1a. Two nibbles: 26 & 0xf = 10 -> 'a', then 26 >> 4 = 1 -> '1'. Reversed gives "1a".
Input: (0,)
Expected Output: "0"
Explanation: Zero is the special case and returns "0" directly (no leading-zero stripping would otherwise leave an empty string).
Hints
- Handle num == 0 as a special case up front, otherwise the loop produces an empty string.
- For negative numbers, add 2^32 (1 << 32) to recover the unsigned 32-bit two's complement value, then convert that.
- Process 4 bits (one hex nibble) at a time: take num & 0xf to index into "0123456789abcdef", then right-shift by 4.
- Build the digits from least-significant to most-significant, then reverse the result before returning.