给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。
知识点:
- 正数右移左边补0, 负数右移左边补1。 所以负数右移一直不会为0,需要用补码转到正数。
解析
第一种,辗转相除法
- 数字如果小于0,则加上模。得到补码
- 然后用辗转相除法就ok啦
class Solution:
def toHex(self, num: int) -> str:
if num < 0:
num += 0x100000000
n = num
maps = [str(i) for i in range(0, 10)] + list('abcdef')
res = ''
if num == 0:
return '0'
while n > 0:
bit = n % 16
n = n // 16
bit = maps[bit]
res = bit + res
return res
第二种, 位运算
class Solution:
def toHex(self, num: int) -> str:
if num < 0:
num += 0x100000000
if num == 0:
return '0'
maps = [str(i) for i in range(0, 10)] + list('abcdef')
n = num
res = ''
while n != 0:
bit = n & 0xf
bit = maps[bit]
n >>= 4
res = bit + res
return res