Skip to content
LC-0405 Easy LeetCode

405. Convert a Number to Hexadecimal

Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 51% Topics: Math, Bit Manipulation
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(logn)
# Space: O(1)

class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        """
        if not num:
            return "0"

        result = []
        while num and len(result) != 8:
            h = num & 15
            if h < 10:
                result.append(str(chr(ord('0') + h)))
            else:
                result.append(str(chr(ord('a') + h-10)))
            num >>= 4
        result.reverse()

        return "".join(result)

Solution from kamyu104/LeetCode-Solutions · MIT