問題描述
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"
補充說明:
一個老生長談的問題,給定一個十進制整數(shù),輸出它的十六進制形式。這里有幾點要求,其一是輸出的字符均為小寫,其二是如果十六進制的高位為0,那么不顯示多余的0,其三是這個數(shù)字是一個32位整形,其四是不能用轉(zhuǎn)換或者格式化的庫。
方案分析
- ok,很清晰,正數(shù)用除數(shù)取余處理。負數(shù)處理成正數(shù)再去處理。
- 負數(shù)如何處理?這里說了,最大是32位整數(shù),那么就加一個32位的最大值就ok了。
python實現(xiàn)
def toHex(self, num):
ret = ''
map = ('0', '1','2','3','4','5','6','7','8','9','a','b','c','d','e','f')
if num == 0:
return '0'
if num < 0:
num += 2**32
while num > 0 :
num, val = divmod(num, 16)
ret += map[val]
return ret[::-1]
方案分析2
- 處理數(shù)字問題,不用位操作簡直毀天滅地。4bits表示一個數(shù)字,按照2進制處理唄。
- 別人的代碼。
python實現(xiàn)2
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0: return '0'
ret = ''
map = ['a', 'b', 'c', 'd', 'e', 'f']
# 32 bit == 4 byte each x char represents 4 bits, half a byte
for i in xrange(8): # at max we have 32 bit integer, so 8 iterations of computing 4 bits in each iteration == 32 bits
cur = num & 0b1111 # get least significant 4 bits, this corresponds to least significant hex char
char = cur if cur < 10 else map[cur - 10] # fetch hex char
ret = str(char) + ret # append hex char to return
num = num >> 4 # erase the 4 bits we just computed for next iteration
pos = 0
while pos < len(ret) and ret[pos] == '0':
pos += 1
return ret[pos:]