描述
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.
Example 1:
Input: num = 26
Output: "1a"
Example 2:
Input: num = -1
Output: "ffffffff"
Note:
-2^31 <= num <= 2^31 - 1
解析
根据题意,就是将十进制转换成十六进制,如果是 0 直接返回 '0' 。如果是负数先将 num 转换成 0xffffffff + 1 + num ,然后将各位的数字找出拼接成字符串,逆序输入即可。
这里为了求的一个数 num (num < 0)的补码,我们记要求的补码为 x ,则有 x + ( -num ) = 0 ,于是 x = 0 + num,在 32 位表示中,0 为 0xffffffff + 1 。
解答
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
if num < 0:
num = 0xffffffff + 1 + num
T = '0123456789abcdef'
r = ''
while num > 0:
m = num % 16
r += T[m]
num //= 16
return r[::-1]
运行结果
Runtime: 16 ms, faster than 70.31% of Python online submissions for Convert a Number to Hexadecimal.
Memory Usage: 13.4 MB, less than 68.75% of Python online submissions for Convert a Number to Hexadecimal.
原题链接:leetcode.com/problems/co…
您的支持是我最大的动力