Skip to content

405 Convert a Number to Hexadecimal

405. Convert a Number to Hexadecimal

题目:

https://leetcode.com/problems/convert-a-number-to-hexadecimal/

难度:

Easy

wikipedia两个page:

十六进制

例子:

4877÷16=304....13(D)

304÷16=19....0

19÷16=1....3

1÷16=0....1

這樣就計到4877(10)=130D(16)

补码

一個數字的二補數就是將該數字作位元反相運算(即一補數反码),再將結果加1。在二補數系統中,一個負數就是用其對應正數的二補數來表示

看给的这个-1的例子

0000 0000 0000 0000 0000 0000 0000 0001

1111 1111 1111 1111 1111 1111 1111 1110 +1

1111 1111 1111 1111 1111 1111 1111 1111

f f f f f f f f

也可以参考这里:

基础03:原码、反码、补码

这里我一开始迷茫和晕了一下,但是随后反应过来,这些数字在电脑里使用二进制存的,而负数也是用二进制的补码存的。所以其实AC代码应当很简单。

参考:

https://github.com/kamyu104/LeetCode/blob/master/Python/convert-a-number-to-hexadecimal.py

AC代码:

class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        """
        if not num :
            return "0"

        result = []
        hexStr ="0123456789abcdef"
        while num and len(result) != 8:
            h = num & 15
            result.append(hexStr[h])
            num >>= 4

        return ''.join(result[::-1])

每次看后四位的结果,把它存起来,比如还是是看4877

它在计算机内部的表示是:

0b1001100001101
num & 15        1101 & 15 = 13(d)
num >>=4        0b100110000
num & 15        0000 & 15 = 0
num >>=4        0b10011
num & 15        10011 & 15 = 9
num >>=4        0001
num & 15        0001 & 15 = 1


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组