Question Link:
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
Solution
We convert each 4 bits of the number from lowest bits to higher. The only thing is how to convert a negative integer. According to Two’s Complement, we can convert negative by coding the negation of a positive number:
- Invert all the bits of the number
- Add one
Implementation
[-]
Python code accepted by LeetCode OJ
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "0"
code = "0123456789abcdef"
res = ""
# Tow's complement negation
if num < 0:
num = (-num ^ 0xffffffff) + 1
# Convert binary to hex
while num != 0:
x = num & 0xf
res = code[x] + res
num = num >> 4
# Return
return res