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
0
s. 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"
Subscribe to see which companies asked this question
最下面的是不要脸版本,当然了,太不要脸了,所以呢,只需要自己实现一下hex这个函数就行
怎么实现呢,那就是一个循环,不断地除以16,然后转化成十六进制就行了
class Solution(object):
def toHex(self, num):
def change(num):
res = ''
hex = ['a','b','c','d','e','f']
for i in num[::-1]:
#print i
if i > 9:
res += hex[i%10]
else:
res += str(i)
return res
def f(num):
#print '```'
res = []
while num > 0:
#print num
res += num % 16,
num /= 16
#print num
return res
if num == 0:
return '0'
if num < 0:
num += (1 << 32)
res = f(num)
#print res
return change(res)