pass: 自己的求解方案,一步一步求解出来
该题求解要求:不能使用库中提供的函数,需要一步一步求解
class Solution:
def toHex(self, num: int) -> str:
def get_strOut(num16New):
strOut = ''
for numSingle in num16New:
if numSingle == 15:
strOut += 'f'
elif numSingle == 14:
strOut += 'e'
elif numSingle == 13:
strOut += 'd'
elif numSingle == 12:
strOut += 'c'
elif numSingle == 11:
strOut += 'b'
elif numSingle == 10:
strOut += 'a'
else:
strOut += str(numSingle)
return strOut
if num >= 0:
num16 = []
while num >= 16:
num16.append(num % 16)
num = num // 16
num16.append(num)
num16New = num16[::-1]
strOut = get_strOut(num16New)
if num < 0:
num1 = -num
num16 = []
while num1 >= 16:
num16.append(num1 % 16)
num1 = num1 // 16
num16.append(num1)
num16_8 = num16[::-1]
num16_8_1 = [0] * 8
num16_8_1[8-len(num16_8):] = num16_8
# print(num16_8_1)
if len(num16_8)==8: # 碰见了转化后已经达到8位了,提前结束
return get_strOut(num16_8)
num16_8_new = []
num16_8_new.append(15)
for j in range(1, len(num16_8_1) ):
num16_8_new.append(15-num16_8_1[j]) # 求反码
#print(num16_8_new)
num16_8_new[-1] += 1
for k in range(len(num16_8_new)-1,0,-1):
if num16_8_new[k] >= 16:
num16_8_new[k] -= 16
num16_8_new[k-1] += 1
strOut = get_strOut(num16_8_new)
return strOut
大佬的解法
自己还是太弱了
ans = []
CONV = "0123456789abcdef"
# 32位2进制数,转换成16进制 -> 4个一组,一共八组
for _ in range(8):
ans.append(num%16) # 按照这个架势好像反码不影响 # -1 % 16 = 15
num //= 16
if not num:
break
return "".join(CONV[n] for n in ans[::-1])
# ans[::-1] 表示进制转换需要倒过来
利用哈希表
有意思的是这个反码的表达,如果是负值
result = ''
hexDict = {0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'a',11:'b',12:'c',13:'d',14:'e',15:'f'}
if num == 0:
return '0'
if num < 0:
num = 16**8 + num
while num > 0:
result = hexDict[num % 16] + result
num //= 16
return result



