easy 10-line python solution with inline explanation


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

  • 0
    K

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


  • 1
    W

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


  • 0
    W

    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


  • 0
    W

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


  • 0
    M

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


  • 1
    S

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


Log in to reply
 

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