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

LeetCode 461: Hamming Distance

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

基本資料
#

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

  • 提交紀錄:Accepted ×2

解題思路
#

兩個位元不同時 XOR 是 1,所以 Hamming distance 就是 x ^ y 裡 1 的個數(Bit Manipulation)。數 1 可以用 bin(z).count("1"),或反覆 z &= z - 1(每次消掉最低的 1)。

我的解法
#

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        z, count = x ^ y, 0
        while z:
            z &= z - 1
            count += 1
        return count

複雜度
#

時間 O(位元數),空間 O(1)。

要特別避免的錯誤
#

  • z & (z - 1) 每次消掉一個 1,迴圈次數等於 1 的個數。

面試口說整理
#

兩個位元不同時 XOR 是 1,我算 x XOR y,再用 z & (z - 1) 一次消掉一個 1 來數個數。時間是 1 的個數。

相關文章

LeetCode 136: Single Number
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 136 解題筆記:x ^ x = 0、x ^ 0 = x,把所有數 XOR 起來,出現兩次的互相抵消,剩下的就是答案
LeetCode 476: Number Complement
·1 分鐘
LeetCode Easy Bit-Manipulation
LeetCode 476 解題筆記:做一個跟 num 一樣長、全部是 1 的遮罩,num ^ mask 就是補數
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 405: Convert a Number to Hexadecimal
·1 分鐘
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 解題筆記:負數先加上 2^32 變成補數,再每次取 4 個位元(% 16)轉成十六進位;0 要特別處理
LeetCode 231: Power of Two
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 解題筆記:2 的次方只有一個位元是 1,n & (n - 1) 會把最低的 1 消掉,結果是 0 就是;n 要是正數