simple python solution that beats 89%, no map or anything


  • 0
    I

    I think this is the method that people are commonly taught to do in university so just wanted to post this. No map or anything :)

    class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        1111...1111
        """
        if num == 0:
            return "0"
        
        if num < 0:
            num = -num
            num ^= 0xffffffff
            num += 1
            
        hex_str = ''
        while num > 0:
            digit = num % 16
            if digit < 10:
                hex_str += str(digit)
            else:
                hex_letter = chr(digit - 10 + ord('a'))
                hex_str += hex_letter
                
            num /= 16
            
        return hex_str[::-1]

  • 0
    Y

    Can you explain what you are doing when num < 0 ?


  • 0
    I

    if num < 0, i am essentially taking the twos compliment of 0, that means I have to invert all the bits and add 1. Unfortunately in python, teh ~ operator does not flip the bits, so i XOR it with a 32 bit integer that is all 1's, which is 0xffffffff, then add 1


  • 0
    Y

    Wouldn't that still be the same negative number?

    For example, if num = -2, which is 0xFFFFFFFD
    after taking -num, it becomes +2, which is 0x00000002
    you xor it with 0xFFFFFFFF, which makes num = 0xFFFFFFFC
    and then you increment it by 1, which makes num 0xFFFFFFFD now. This is exactly the same number as it is before and it is still negative.


  • 0
    I

    I have to convert it to a positive equivalent since the 2nd loop is while the number is > 0


  • 0
    I

    I just tried what you said in the python shell like so: http://imgur.com/a/A5SEl
    seems like python does not make it a negative number


  • 0
    Y

    I think somehow python converts it to a long value (64 bit) instead of an int value (32 bit). When you xor with 0xFFFFFFFF, it's actually xoring with 0x00000000FFFFFFFF


  • 0
    I

    Yea I guess. really weird lol


Log in to reply
 

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