Convert a Number to Hexadecimal

Problem Id: 405 Difficulty: Easy


Intuition

Solution


class Solution:
    def toHex(self, num: int) -> str:
        if num == 0:
            return "0"
        elif num < 0:
            num = 2 ** 32 + num

        mapping = string.digits + string.ascii_lowercase

        ans = ""
        while num:
            ans = mapping[num % 16] + ans
            num = num // 16
        return ans