LeetCode: 405. 数字转换为16进制

给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。

知识点:

  • 正数右移左边补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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值