Convert a Number to Hexadecimal
What is this problem about?
The Convert a Number to Hexadecimal interview question asks you to convert an integer to its hexadecimal (base-16) string representation. For negative integers, you must use the two's complement method. You cannot use built-in library functions for base conversion.
Why is this asked in interviews?
Companies like Meta and Amazon ask the Convert a Number to Hexadecimal coding problem to test a candidate's comfort with Bit Manipulation and low-level data representation. It evaluates if you understand how computers store signed integers and how to extract 4-bit chunks (nibbles) from a 32-bit word.
Algorithmic pattern used
This utilizes the Math, String, Bit Manipulation interview pattern.
- Use a lookup string: "0123456789abcdef".
- Process the integer 4 bits at a time.
- Use a bitwise AND with 15 (0xf) to get the value of the rightmost 4 bits.
- Shift the number right by 4 bits (>>> unsigned shift) after each step.
- Handle the 0 case separately.
Example explanation
Input: 26 (binary 0001 1010)
- 26 AND 15 = 10. Char at index 10 is 'a'. Result: "a".
- Shift right 4 bits: binary 0001 (decimal 1).
- 1 AND 15 = 1. Char at index 1 is '1'. Result: "1a".
- Shift right 4 bits: 0. Stop.
Output: "1a".
Common mistakes candidates make
- Handling negative numbers: Trying to use abs() and manual sign handling instead of leveraging the bitwise representation (two's complement).
- Unsigned shift: Using >> (signed shift) instead of >>> (unsigned shift), which will cause an infinite loop for negative numbers as the sign bit is preserved.
- Leading zeros: Adding unnecessary zeros to the front of the string.
Interview preparation tip
Always use the Unsigned Right Shift (>>>) for bit-extraction problems involving potentially negative numbers. It ensures that 0s are shifted in from the left, eventually making the number 0 and terminating your loop.