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).
Input: (-1,)
Expected Output: "ffffffff"
Explanation: -1 in 32-bit two's complement is 0xFFFFFFFF. Adding 1<<32 to -1 yields 4294967295 = ffffffff.
Input: (255,)
Expected Output: "ff"
Explanation: 255 = 0xff, exactly one byte: two 'f' nibbles.
Input: (16,)
Expected Output: "10"
Explanation: 16 = 0x10. 16 & 0xf = 0 -> '0', 16 >> 4 = 1 -> '1'. Reversed gives "10".
Input: (2147483647,)
Expected Output: "7fffffff"
Explanation: INT_MAX = 2^31 - 1 = 0x7FFFFFFF.
Input: (-2147483648,)
Expected Output: "80000000"
Explanation: INT_MIN = -2^31. Adding 1<<32 gives 2147483648 = 0x80000000.
Input: (1,)
Expected Output: "1"
Explanation: Single nibble: 1 & 0xf = 1 -> '1', then 1 >> 4 = 0 ends the loop.
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.