↓快轉到主要內容
  1. LeetCode/

LeetCode 405: Convert a Number to Hexadecimal

·1 分鐘· ·
LeetCode Easy Math String Bit-Manipulation
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-23

  • 提交紀錄:Runtime Error ×2 → Wrong Answer ×2 → Accepted

解題思路
#

十六進位每一位就是 4 個位元(Bit Manipulation,也是 Math 模板七的進位轉換)。負數用 32 位元補數表示,num & 0xffffffff(等於加上 2^32)就是對應的正數。接著每次取 num & 15 查表、num >>= 4,直到 0。num = 0 時迴圈不會執行,要回傳 "0"。

我的嘗試
#

  • 第一版迴圈條件寫成 num > 15,最後一位沒有寫進去,num = 0 時也回傳空字串。
  • 補上 0 的特例後,負數沒有處理:-9 回傳空字串,答案 "fffffff7"。加上 num += 2**32 就 AC 了。

正確解法
#

class Solution:
    def toHex(self, num: int) -> str:
        if num == 0:
            return "0"
        num &= 0xFFFFFFFF
        digits = "0123456789abcdef"
        res = []
        while num:
            res.append(digits[num & 15])
            num >>= 4
        return "".join(reversed(res))

複雜度
#

時間 O(8),空間 O(1)。

要特別避免的錯誤
#

  • 負數要先轉成 32 位元的補數。
  • 迴圈條件是 num > 0,num > 15 會少最後一位。
  • 0 要回傳 "0"。

面試口說整理
#

負數先跟 0xffffffff 做 AND 變成 32 位元補數對應的正數,之後每次取最低的 4 個位元查表、右移 4 位,最後反轉;0 直接回傳。最多 8 位。

相關文章

LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 342: Power of Four
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 解題筆記:先確認是 2 的次方,再確認那個 1 在偶數位:n & 0x55555555 != 0,或 n % 3 == 1
LeetCode 389: Find the Difference
·1 分鐘
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 解題筆記:t 比 s 多一個字元,把兩個字串的所有字元 XOR 起來,成對的抵消,剩下的就是多的那個
LeetCode 412: Fizz Buzz
·1 分鐘
LeetCode Easy Math String Simulation
LeetCode 412 解題筆記:先判斷 15 的倍數,再判斷 5 和 3;倍數要用 %,不是 //
LeetCode 231: Power of Two
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 解題筆記:2 的次方只有一個位元是 1,n & (n - 1) 會把最低的 1 消掉,結果是 0 就是;n 要是正數
LeetCode 171: Excel Sheet Column Number
·1 分鐘
LeetCode Easy Math String
LeetCode 171 解題筆記:從左到右 res = res × 26 + 字母的值(A = 1)