class Solution:
    def toHex(self, x: int) -> str:
        """tc O(lgN) sc O(1)
        """
        res = ''
        if x == 0:
            return '0'
        d = '0123456789abcdef'
        res = ''
        #for i in range(8):
        while x and len(res) < 8:  #must add len(res) < 8 else it will loop forever when x is negtive 
            low = x & 15
            c = d[low]
            res = c + res 
            x = x >> 4
            if x == 0:break  #or terminate when x == 0         
        return res #res.lstrip('0') # remove leading zeros