9.2 位運算基礎問題
461. Hamming Distance
題目描述
給定兩個十進制數字,求它們二進制表示的漢明距離(Hamming distance,即不同位的個數)。
輸入輸出範例
输入是两个十进制整数,输出是一个十进制整数,表示两个输入数字的汉明距离。
Input: x = 1, y = 4
Output: 2
在這個範例中,1 的二進制是 0001,4 的二進制是 0100,一共有兩位不同。
題解
對兩個數進行按位異或操作,統計結果中有多少個 1 即可。
- C++
- Python
int hammingDistance(int x, int y) {
int diff = x ^ y, dist = 0;
while (diff != 0) {
dist += diff & 1;
diff >>= 1;
}
return dist;
}
def hammingDistance(x: int, y: int) -> int:
diff = x ^ y
dist = 0
while diff != 0:
dist += diff & 1
diff = diff >> 1
return dist
190. Reverse Bits
題目描述
給定一個十進制正整數,輸出它在二進制下的翻轉結果。