python 负数取反加1


  • 0
    J
    class Solution(object):
        def toHex(self, num):
            """
            :type num: int
            :rtype: str
            """
            if num == 0:
                return '0'
            if num < 0:
                num = (-num ^ 0xffffffff) + 1
                
            ans = []
            dic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
            while num > 0:
                digit = num % 16
                num /= 16
                
                if 9 < digit < 16:
                    digit = dic[digit]
                else:
                    digit = str(digit)
                ans.append(digit)
            return ''.join(ans[::-1])
    

Log in to reply
 

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