Convert a Number to Hexadecimal
Problem
Given a signed 32-bit integer num, return its lowercase hexadecimal representation. Negative numbers use two's complement; do not use any library conversion.
num = 26"1a"def to_hex(num):
if num == 0: return "0"
if num < 0: num += 1 << 32
digits = "0123456789abcdef"
out = ""
while num > 0:
out = digits[num & 0xf] + out
num >>= 4
return out
function toHex(num) {
if (num === 0) return "0";
if (num < 0) num = num >>> 0;
const digits = "0123456789abcdef";
let out = "";
while (num > 0) {
out = digits[num & 0xf] + out;
num = num >>> 4;
}
return out;
}
class Solution {
public String toHex(int num) {
if (num == 0) return "0";
char[] digits = "0123456789abcdef".toCharArray();
StringBuilder sb = new StringBuilder();
while (num != 0) {
sb.append(digits[num & 0xf]);
num >>>= 4;
}
return sb.reverse().toString();
}
}
string toHex(int num) {
if (num == 0) return "0";
string digits = "0123456789abcdef", out;
unsigned int n = (unsigned int) num;
while (n > 0) {
out = digits[n & 0xf] + out;
n >>= 4;
}
return out;
}
Explanation
Hexadecimal is just binary grouped into chunks of 4 bits (called nibbles), where each nibble maps to one hex character 0-9a-f. So converting a number to hex means repeatedly peeling off its lowest 4 bits and translating each group.
The loop reads the lowest nibble with num & 0xf — the mask 0xf is 1111, so this keeps only the bottom four bits, a value from 0 to 15. We use that as an index into "0123456789abcdef" to get the hex digit, then num >>= 4 drops those four bits so the next nibble moves into place.
Because we read the digits from least-significant first, each new digit is prepended to the result (or the result is reversed at the end), so the final string reads in the correct high-to-low order.
Negative inputs are handled with two's complement: treating the number as an unsigned 32-bit pattern (e.g. num >>> 0 in JS, or num += 1 << 32 in Python) so the bit layout matches what hardware stores.
Example: num = 26 is 11010 in binary. The low nibble 1010 is 10 → 'a'; shifting leaves 1, whose nibble is 1 → '1'. Prepending gives "1a".