Python實現"數字轉換為十六進位制"的方法
阿新 • • 發佈:2018-12-16
給定一個整數,寫一個演算法將它轉換為16進位制,對於負數,可以使用two’s complement方法
注意:
16進位制(a-f)只包括小寫字母
十六進位制字串中不能包含多餘的前導零。如果要轉化的數為0,那麼以單個字元'0'
來表示;對於其他情況,十六進位制字串中的第一個字元將不會是0字元。
給定的數確保在32位有符號整數範圍內。
不能使用任何由庫提供的將數字直接轉換或格式化為十六進位制的方法。
Example 1:
Input: 26 Output: "1a"
Example 2:
Input: -1 Output: "ffffffff"
1:自然數轉16進位制的方法和轉二進位制一樣.負數則先取反、再轉31位二進位制、再反碼、再反碼+1、再加上符號位(此時32位)、最後再轉16進位制
def toHex(self, num): """ :type num: int :rtype: str """ chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'} if num >= 0: hexStr = "" while num >= 16: rest = num % 16 hexStr = chaDic.get(rest, str(rest)) + hexStr num //= 16 hexStr = chaDic.get(num, str(num)) + hexStr return hexStr else: if num == -2147483648: #特殊情況,負數最大值 return "80000000" num = -num #負數取反 bitList = [0] * 31 tail = 30 while num >= 2: #數字轉二進位制 rest = num % 2 bitList[tail] = rest tail -= 1 num //= 2 bitList[tail] = num for i in range(31): # 反碼 bitList[i] = 1 if bitList[i] == 0 else 0 tail = 30 add = 1 while add + bitList[tail] == 2: #反碼加1 bitList[tail] = 0 tail -= 1 bitList[tail] = 1 bitList = [1] + bitList #新增負號 print bitList hexStr = "" for i in range(0, 32, 4): #二進位制轉16進位制 add = 0 for j in range(0, 4): add += bitList[i + j] * 2 ** (3 - j) hexStr += chaDic.get(add, str(add)) return hexStr