Coding questions · Meta
Convert 32-bit integer to hexadecimal
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.
Problem
Given a 32-bit signed integer num, return its hexadecimal representation as a string.
Requirements
- Use lowercase letters
a-f. - Do not include leading zeros (unless the value is exactly zero).
- For negative numbers, return the hexadecimal representation of the corresponding 32-bit two's complement value.
Input
- Integer
numin range[-2^31, 2^31 - 1]
Output
- A string containing the hexadecimal representation.
Examples
num = 26→"1a"num = 0→"0"num = -1→"ffffffff"
Follow-ups (optional)
- Implement without using built-in base conversion utilities (e.g., no
toString(16)/format).
Convert 32-bit Integer to Hexadecimal
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.
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.