Two Python solutions


  • 1
    C

    I use num += 2**32 to take care of negative number

    solution 1: use divmod. ~ 75ms
    Here I start by building a string. I also tried to use a list and convert list to string and find it's actually almost 30ms faster (48ms).

        def toHex(self, num):
            ret = ''
            letter = ('0', '1','2','3','4','5','6','7','8','9','a','b','c','d','e','f')
            if num == 0: return '0'
            if num < 0: num += 2**32
            while num > 0 :
                num, val = divmod(num, 16)
                ret += letter[val]
            return ret[::-1]
    

    solution 2: bit manipulation, check each 4 bits. ~78ms

        def toHex(self, num):
            ret = ''
            letter = ('0', '1','2','3','4','5','6','7','8','9','a','b','c','d','e','f')
            if num == 0: return '0'
            if num < 0: num += 2**32
            while num != 0:
                ret = letter[num&15] + ret
                num >>= 4
            return ret
    

Log in to reply
 

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