python 负数十六进制_yiduobo的每日leetcode 405.数字转换为十六进制数

772cfec1ed1653d717e1431e3dec3afa.png

祖传的手艺不想丢了,所以按顺序写一个leetcode的题解。计划每日两题,争取不卡题吧

405.数字转换为十六进制数https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal/

比较基础的题目,不断模16然后将10到15转化为a到f即可。

对于负数来说,则是先计算正数的十六进制表示,然后取反取补。

最后附上python代码:

class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        """
        
        if num == -2147483648:
            return '80000000'
        if num == 0:
            return '0'

        neg_flag = False
        if num < 0:
            neg_flag = True
            num = -num

        num_list = [0] * 8
        pos = -1
        while num:
            num_list[pos] = num % 16
            num /= 16
            pos -= 1

        if neg_flag:
            num_list = [15 - x for x in num_list]
            num_list[-1] += 1
            pos = -1
            while num_list[pos] == 16:
                num_list[pos] -= 16
                num_list[pos - 1] += 1
                pos -= 1

        zero_flag = True
        char_list = []
        for x in num_list:
            if zero_flag and x == 0:
                continue
            zero_flag = False
            if x < 10:
                char_list.append(str(x))
            else:
                char_list.append(chr(x + 87))
        
        return ''.join(char_list)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值