2025-07-29 15:27:23 +0000 UTC

Convert a Number to Hexadecimal

Code

class Solution:
    def toHex(self, num: int) -> str:
        if num >=0 and num < 10:
            return str(num)
        if num < 0:
            num = (1 << 32) + num
        symbols = "0123456789abcdef"
        res = []
        while num > 0:
            mod = num % 16
            res.append(symbols[mod])
            num //= 16
        return "".join(reversed(res))