Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

1
2
3
4
5
Input:
26
Output:
"1a"

Example 2:

1
2
3
4
5
Input:
-1
Output:
"ffffffff"

思路

我们利用位运算来解决这个问题。所有的数在内存中都是以二进制的方式存储的。二进制转十六进制的方法非常简单,只要每四位二进制数转换成一位十六进制数即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import math
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
hexmap = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
reslist = []
mask = 0xf
flag = 0
iter = 0
# 注意小于0的情况
if (num < 0):
num = num & 0x7fffffff
iter = 7
flag = 1
elif(num == 0):
return '0'
else:
iter = int(math.log(abs(num), 16))
reslist.append( hexmap[num & mask] )
for i in range(iter):
num = num >> 4
tmp = num & mask
if (i == iter-1 and flag == 1):
tmp += 8
reslist.append( hexmap[tmp] )
reslist.reverse()
res = ''.join(reslist)
return res