leetcode 405. Convert a Number to Hexadecimal
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
- All letters in hexadecimal (
a-f
) must be in lowercase. - The hexadecimal string must not contain extra leading
0
s. If the number is zero, it is represented by a single zero character'0'
; otherwise, the first character in the hexadecimal string will not be the zero character. - The given number is guaranteed to fit within the range of a 32-bit signed integer.
- You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input: 26 Output: "1a"
Example 2:
Input: -1 Output: "ffffffff"
>>> hex(123)
'0x7b'
>>> hex(123)[2:]
'7b'
>>> hex(1)
'0x1'
>>> hex(0)
'0x0'
>>> bin(0)
'0b0'
>>> bin(1)
'0b1'
1 2 3 4 5 6 7 8 9 10 11 | class Solution( object ): def toHex( self , num): """ :type num: int :rtype: str """ # use recurively if num < 0 : return hex (num + ( 1 << 32 ))[ 2 :] else : return hex (num)[ 2 :] |
注:Main ideal is to flip the negative number to positive by using following code: # num = num + 2**32
负数的binary 表示就是num + 2**32
的正数表示。因为python里hex和bin都是针对正数有效。
>>> bin(-1)
'-0b1'
>>> bin(-12)
'-0b1100'
>>> hex(-12)
'-0xc'
>>> hex(-123)
'-0x7b'
因此,自己写的话,可以:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Solution( object ): def toHex( self , num): """ :type num: int :rtype: str """ # use recurively if num = = 0 : return "0" if num < 0 : num + = ( 1 << 32 ) ans = "" hex_s = "0123456789abcdef" while num ! = 0 : ans = hex_s[num & 0xf ] + ans num = num >> 4 return ans |
其他解法:
1 2 3 4 5 6 7 8 9 10 | def toHex( self , num): if num = = 0 : return '0' mp = '0123456789abcdef' # like a map ans = '' for i in range ( 8 ): n = num & 15 # this means num & 1111b c = mp[n] # get the hex char ans = c + ans num = num >> 4 return ans.lstrip( '0' ) #strip leading zeroes |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-04-14 echo 到 stderr