Python solution


  • 3
      def toHex(self, num):
        ans = []
        dic = {10:"a", 11:"b", 12:"c", 13:"d", 14:"e", 15:"f"}
        if num == 0:
            return "0"
        if num < 0:
            num = num + 2**32
    
        while num > 0:
            digit = num % 16
            num = (num-digit)/16
            if  digit > 9 and digit < 16:
                digit = dic[digit]
            else:
                digit = str(digit)
            ans.append(digit)
        return "".join(ans[::-1]
    
    Main ideal is to flip the negative number to positive by using following code:
    # num = num + 2**32
    

    Things need to know
    In two's complement:
    zero is 000....0000 = 0
    Most negative number is -2^(n-1)
    Most positive number is 2^(n-1) -1


  • 0
    A

    @Zura
    Could you please explain

    if num < 0:
            num = num + 2**32
    

    Thanks :)


  • 0
    K

    Why not use

    digit += chr(97 + reminder - 10)


  • 0
    G
        if num < 0:
            cur = (-num ^ 0xffffffff) + 1
        else:
            cur = num

  • 0
    D
        if num==0:
            return "0"
        hexes = {10:"a", 11:"b", 12:"c", 13:"d", 14:"e", 15:"f"}
        strn = ""
        if num<0:
            num+=4294967296
        while num>0:
            temp = num%16
            if temp>=10:
                strn=hexes[temp]+strn
            else:
                strn=str(temp)+strn
            num/=6
        return strn
    

    this is my take on it, I got a similar solution. It was pretty fast (97%)


Log in to reply
 

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