# easy 10-line python solution with inline explanation

• ``````    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
``````

• why for i in range(8)?
where does 8 come from?

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

• if num==0: return '0'
mp = '0123456789abcdef' # like a map
ans = ''
for i in range(8):
ans=mp[ num & 15 ]+ans # this means num & 1111b
num = num >> 4
return ans.lstrip('0') #strip leading zeroes on the left

after modifying the code,time is shorter

• I have a question : for negetive integer, how this method works?

• @kid821654
int has 32 bits
one byte has 4 bits
so, you need to loop 8 times

• @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.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.