def toHex(self, num):
if num==0: return '0'
mp = '0123456789abcdef' # like a map
ans = ''
for i in range(8):
n = num & 15 # this means num & 1111b
c = mp[n] # get the hex char
ans = c + ans
num = num >> 4
return ans.lstrip('0') #strip leading zeroes
easy 10line python solution with inline explanation

@kid821654 I think OJ considers 32bit int. One hex number is represented by 4 bits. Then 32/4=8.


@weiyang__ because for negative, the number is already in two’s complement representation in binary, so what we need to do is to transfer binary into Hexa, that is why it can handle negative numbers.