Hamming Distance (E)
題目
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
題意
計算兩個整數之間的漢明距離,即二進制對應位不相等的個數,
思路
可以直接移位判斷,也可以異或后統計1的個數,
代碼實作
Java
移位判斷
class Solution {
public int hammingDistance(int x, int y) {
int distance = 0;
while (x != 0 || y != 0) {
if ((x & 1) != (y & 1)) {
distance++;
}
x >>= 1;
y >>= 1;
}
return distance;
}
}
異或
class Solution {
public int hammingDistance(int x, int y) {
int distance = 0;
int xor = x ^ y;
while (xor != 0) {
if ((xor & 1) == 1) distance++;
xor >>= 1;
}
return distance;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/27714.html
標籤:其他
上一篇:資料結構-堆疊
