leetcode with python:405. Convert a Number to Hexadecimal

题目:

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

给定一数,将其转为16进位制

这题比较需要特别注意的点大概是负数的处理吧

class Solution:    def toHex(self, num: int) -> str:        if num==0: #防止num=0            return "0"        if num<0: #负数转换            num=num+2**32        ans=""        d={10:'a',11:'b',12:'c',13:'d',14:'e',15:'f'}#10~15的对应表示                while num:                        temp=num%16                        if temp>9:                ans=d[temp]+ans            else:                ans=str(temp)+ans                            num=num//16                    return ans

十六进位负数的表示是将其+2^32后再进行转换
将num不断%16,//16找出每一位的值
再将其组合为字串回传
最后执行时间31ms(faster than 91.59%)

上面那个解不是这题的重点
我在讨论区看到使用位元运算的解
我认为这才是这题的最佳解

class Solution:    def toHex(self, num: int) -> str:        if num==0:             return '0'        s = '0123456789abcdef'                 ans = ''        for i in range(8):            x=num & 15                  temp =s[x]                       ans = temp + ans            num = num >> 4                    return ans.lstrip('0')

我们可以发现2进位每4位刚好可以判断16进位的一位
于是我们将其&15(1111),刚好可以得到末四位代表的值
之后>>4,看下一个4位组合代表的值
由于我们知道二进位表示最多有32位(测资限制)
所以迴圈跑8次(8 * 4=32)
将每4位值对应的字元一一放入ans空字串
最后将ans左端的0全部去除后回传
最后执行时间19ms(faster than 99.89%)

明天起几天会出游,应该会断更个3,4天吧
小休一下

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章