### 405. 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代码应当很简单。 参考: 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 ```