Convert a Number to Hexadecimal (LeetCode 405): Solution and Explanation
Given a 32-bit signed integer, return its lowercase hexadecimal string without leading zeros. Negative numbers are written using their 32-bit two's complement pattern, so -1 is "ffffffff".
Intuition
Base 16 and base 2 line up perfectly: 16 is 2 to the 4th, so every hex digit stands for exactly 4 bits. A 32-bit integer is 8 nibbles, and the hex string is just those 8 nibbles written as digits, with the leading zero nibbles dropped.
That means you never need division. n & 15 keeps the lowest 4 bits, which is the last hex digit. Shifting right by 4 throws that nibble away and brings the next one down. Repeat until n is 0.
Negative numbers are the only trap. The problem wants the two's complement bit pattern, so you must treat the 32 bits as an unsigned value. In Python that means masking with 0xFFFFFFFF; in Java, JavaScript and Go use an unsigned shift or an unsigned type. With a signed arithmetic shift a negative number never reaches 0 and the loop runs forever.
Approach: Nibble by nibble
- If
numis 0, return "0" because the loop would produce no digits. - Convert
numto its unsigned 32-bit patternn. - While
nis not 0, appenddigits[n & 15]and shiftnright by 4. - The digits were produced lowest first, so reverse them and return the string.
Step-by-step example
num = 26
- 26 is not 0 and not negative, so n = 26, binary 0001 1010.
- n & 15 = 1010 = 10, digit 'a'. Output so far: a. Shift: n = 1.
- n & 15 = 0001 = 1, digit '1'. Output so far (right to left): 1a. Shift: n = 0.
- n is 0, so the loop stops. The six upper nibbles were all zero and produced no leading zeros.
- Reverse the collected digits [a, 1] to get "1a".
Code: Python, Java, C++
1class Solution:
2 def toHex(self, num: int) -> str:
3 if num == 0:
4 return "0"
5 digits = "0123456789abcdef"
6 num &= 0xFFFFFFFF
7 out = []
8 while num:
9 out.append(digits[num & 15])
10 num >>= 4
11 return "".join(reversed(out))1class Solution {
2 public String toHex(int num) {
3 if (num == 0) {
4 return "0";
5 }
6 String digits = "0123456789abcdef";
7 long n = num & 0xFFFFFFFFL;
8 StringBuilder sb = new StringBuilder();
9 while (n != 0) {
10 sb.append(digits.charAt((int) (n & 15)));
11 n >>= 4;
12 }
13 return sb.reverse().toString();
14 }
15}1class Solution {
2public:
3 string toHex(int num) {
4 if (num == 0) {
5 return "0";
6 }
7 string digits = "0123456789abcdef";
8 unsigned int n = num;
9 string out;
10 while (n != 0) {
11 out += digits[n & 15];
12 n >>= 4;
13 }
14 reverse(out.begin(), out.end());
15 return out;
16 }
17};Time and space complexity
O(1)
A 32-bit number has 8 nibbles, so the loop runs at most 8 times.
O(1)
The output has at most 8 characters.
Other approaches
Repeated division by 16 (time O(1), space O(1))
Take n % 16 and set n //= 16 after first adding 2^32 to negative inputs. It is the same idea written with arithmetic instead of bit operations.
Fixed 8 nibbles, then strip zeros (time O(1), space O(1))
Read all 8 nibbles from the top with (num >> (4 * k)) & 15 for k from 7 down to 0, skipping zeros until the first non-zero digit. It avoids the reverse but needs care for num = 0.
Common mistakes
- Using a signed right shift on a negative number. In Java or JavaScript
>>keeps copying the sign bit, so n never becomes 0. Use>>>or an unsigned type. - Forgetting the num = 0 case, which returns an empty string from the loop.
- In Python, not masking with 0xFFFFFFFF. Python integers are unbounded, so -1 >> 4 stays -1 forever.
Frequently asked questions
Why does -1 become ffffffff?
In 32-bit two's complement, -1 has all 32 bits set. Each group of four 1 bits is 15, which is the digit f, so there are eight f digits.
Why reverse at the end?
n & 15 reads the lowest nibble first, which is the rightmost digit. Collecting right to left and reversing once is simpler than inserting at the front each time.
Can there be leading zeros?
No. The loop stops as soon as the remaining value is 0, so zero nibbles above the highest set bit are never turned into digits.