链接:
https://leetcode.cn/problems/convert-a-number-to-hexadecimal/description/
分析:
实话实说,我最怕编码类问题了,因为我真的不会,当时读大学的时候也没学好这块。
我的思路是:
首先对数据进行分类,分成正数、负数和零来分别进行处理。
如果是0,直接返回0就好了。
正数的话,适合除N取余法。
负数的话,可以先转换成正数,然后先转换成反码,然后再转换成补码。
但是,这样转换要注意边界问题,比如给定-2147483648,题目要求32位,那转换成正数2147483648就溢出了,所以我们要预留4位二进制数当溢出余量(本题为36位),等计算完再删掉溢出余量就好了。
代码:
class Solution: def toHex(self, num: int) -> str: if num == 0: return '0' elif num > 0: return self.int2x(num, 16) else: minus_b = self.int2x(abs(num), 2) b = self.bin2bu(minus_b, flag=True) return self.bin2hex(b) def int2x(self, num, radix): table2 = [0, 1] table16 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'] table = table2 if radix == 2 else table16 res = [] ds = num while ds != 0: next_ds = ds // radix ys = ds % radix res.append(str(table[ys])) ds = next_ds return ''.join(res[::-1]) def bin2bu(self, b, flag=False): tmp = list(b) while len(tmp) < 36: tmp.insert(0, '0') if flag: tmp[0] = '1' for i in range(1, len(tmp)): if tmp[i] == '1': tmp[i] = '0' else: tmp[i] = '1' remains = 1 for i in range(len(tmp)-1, -1, -1): c_tmp = int(tmp[i]) + remains if c_tmp == 2: tmp[i] = '0' remains = 1 elif c_tmp == 1: tmp[i] = '1' remains = 0 else: tmp[i] = '0' remains = 0 return ''.join(tmp) def bin2hex(self, b): table16 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'] res = '' flag = False for i in range(0, len(b), 4): tmp = b[i:i+4] val = 8 * int(tmp[0]) + 4 * int(tmp[1]) + 2 * int(tmp[2]) + int(tmp[3]) if val > 0: flag = True if flag: res += str(table16[val]) return res[1:]
标签:tmp,十六进制,转换,res,self,405,num,return,ds From: https://www.cnblogs.com/bjfu-vth/p/17653705.html