405. Convert a Number to Hexadecimal.md 2.2 KB
Newer Older
K
KEQI HUANG 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
### 405. Convert a Number to Hexadecimal

题目:

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

难度:

Easy



wikipedia两个page:



[十六进制](https://zh.wikipedia.org/wiki/十六进制#.E5.8D.81.E9.80.B2.E5.88.B6.E8.BD.89.E5.8D.81.E5.85.AD.E9.80.B2.E5.88.B6)

例子:

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

304÷16=19....0

19÷16=1....3

1÷16=0....1

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



[补码](https://zh.wikipedia.org/wiki/二補數)

> 一個數字的二補數就是將該數字作[位元](https://zh.wikipedia.org/wiki/%E4%BD%8D%E5%85%83)[反相](https://zh.wikipedia.org/w/index.php?title=%E5%8F%8D%E7%9B%B8&action=edit&redlink=1)運算(即[一補數](https://zh.wikipedia.org/wiki/%E4%B8%80%E8%A3%9C%E6%95%B8)或[反码](https://zh.wikipedia.org/wiki/%E5%8F%8D%E7%A0%81)),再將結果加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:原码、反码、补码](https://higoge.github.io/2015/07/02/basic03/)



这里我一开始迷茫和晕了一下,但是随后反应过来,这些数字在电脑里使用二进制存的,而负数也是用二进制的补码存的。所以其实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

```