Solution 1 - Bit Manipulation (Nibble Extraction)
Extract 4-bit nibbles (base-16 digits) and map to hex chars; mask to 32-bit for negatives.
Extract 4-bit nibbles (base-16 digits) and map to hex chars; mask to 32-bit for negatives.
""" 0405.1 - Convert a Number to Hexadecimal - Solution 1 - Bit Manipulation """
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return "0"
num &= 0xFFFFFFFF
hex_chars = "0123456789abcdef"
out = []
while num:
out.append(hex_chars[num & 0xF])
num >>= 4
return "".join(reversed(out))
if __name__ == "__main__":
print(Solution().toHex(26)) # 1a