Title:
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
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.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
方法一:58ms
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
dict = {10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f'}
if num == 0:
return '0'
if num < 0:
num += 2**32
s = ''
s1 = []
if num > 0 and num < 10:
return str(num)
elif num >=10 and num < 16:
return dict[num]
while num >= 16:
num, res =divmod(num, 16)
s1.append(res)
s1.append(num)
for i in s1:
if i < 10:
s = str(i) + s
else:
s = dict[i] + s
return s
方法二:42ms
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
# def get_hex(m, num):
# res = []
# while num > 0:
# res.append(MAP[num % 16])
# num = num / 16
# res = ''.join(res[::-1])
# return res
# def reverse(m, r_m, num):
# res = []
# for n in num:
# res.append(m[15 - r_m[n]])
# final = ['f'] * 8
# for i, r in enumerate(res[::-1]):
# final[7-i] = r
# return final
# def add_one_on_last(m, r_m, num):
# c = False
# if num[7] == 'f':
# num[7] = '0'
# c = True
# else:
# num[7] = m[r_m[num[7]] + 1]
# copy_num = num
# if c:
# for i, n in enumerate(copy_num[-2::-1]):
# tmp = r_m[n] + 1
# if tmp == 16:
# num[6-i] = '0'
# else:
# num[6-i] = m[r_m[num[6-i]] + 1]
# break
# return num
# if num == 0:
# return '0'
# MAP = {
# i: str(i) for i in range(0,10)
# }
# MAP[10] = 'a'
# MAP[11] = 'b'
# MAP[12] = 'c'
# MAP[13] = 'd'
# MAP[14] = 'e'
# MAP[15] = 'f'
# reverse_map = {v: k for k, v in MAP.items()}
# #print(reverse_map)
# tmp_num = num if num > 0 else -num
# res = get_hex(MAP, tmp_num)
# if num < 0:
# #print(res)
# res = reverse(MAP, reverse_map, res)
# #print(res)
# res = add_one_on_last(MAP, reverse_map, res)
# return ''.join(res)
if num==0: return '0'
mp = '0123456789abcdef' # like a map
ans = ''
for i in range(8):
n = num % 16 # this means num & 1111b
c = mp[n] # get the hex char
ans = c + ans
num = num >> 4
return ans.lstrip('0') #strip leading zeroes
方法三: 35ms
class Solution(object):
re = {}
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if 0 <= num < 10:
return str(num)
if 10 <= num < 16:
return chr(ord('a') + num - 10)
if num not in self.re:
if num < 0:
self.re[num] = self.toHex(2**32+num)
else:
res = num % 16
val = self.toHex(num/16)
self.re[num] = val + self.toHex(res)
return self.re[num]