405 Convert a Number to Hexadecimal

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"

Example 2:

Input: num = -1
Output: "ffffffff"

Constraints:

  • -231 <= num <= 231 - 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def toHex(self, num: int) -> str:
        if num == 0:
            return '0'
        d = '0123456789abcdef'
        res = ''
        for i in range(8):
            res = d[num % 16] + res
            num >>= 4
        return res.lstrip('0')
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
func toHex(num int) string {
    // fix to 32-bit int
	num32 := int32(num)
	if num32 == 0 {
		return "0"
	}
	result := ""
	for num32 != 0 {
		digit := num32 & 0xf
		var digitChar string
		if digit > 9 {
			digitChar = string(digit - 10 + int32('a'))
		} else {
			digitChar = strconv.Itoa(int(digit))
		}
		result = digitChar + result
		// unsigned shift
		num32 = int32(uint32(num32) >> 4)
	}
	return result
}