describe

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

Example 1:

Input: num = 26
Output: "1a"	
Copy the code

Example 2:

Input: num = -1
Output: "ffffffff"
Copy the code

Note:

-2^31 <= num <= 2^31 - 1
Copy the code

parsing

Convert decimal to hexadecimal, and return ‘0’ if 0. If it is a negative number, convert num to 0xffffFFFF + 1 + num, then concatenate the digits into a string, and enter them in reverse order.

X + (-num) = 0, so x = 0 + num, 0 = 0xffffFFFF + 1 in 32-bit representation.

answer

class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0:
            return '0'
        if num < 0:
            num = 0xffffffff + 1 + num
        T = '0123456789abcdef'
        r = ''
        while num > 0:
            m = num % 16
            r += T[m]
            num //= 16
        return r[::-1]
        	      
		
Copy the code

The results

Given in the Python online submissions for converting a Number to Hexadecimal. Given in the Python online submissions for converting a Number to Hexadecimal.Copy the code

Original link: leetcode.com/problems/co…

Your support is my biggest motivation