LeetCode 461. Hamming Distance(汉明距离)
题目描述
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 < 2^(31).
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.
解法一
思路
汉明距离,即两个数的二进制表示中对应位上数字(0/1)不相同的个数。如01101
和01011
的汉明距离即为2,因其仅第1和第2位(从右至左,0开始)不相同。
很容易想到这题应该用异或,即
01101 ^ 01011 = 00110
现在数00110
中1的个数就好了。
怎么数1的个数?这里有个简单的方法:
num = 0b00110
count = 0
while num:
num &= num - 1
count += 1
print(count)
每次num &= num - 1
,num
二进制值的最低位1都会变成0,即每次去掉一个1,直到其值为0,举个例子看看:
00110 & 00101 = 00100
00100 & 00011 = 00000
这样汉明距离就算出来啦~
Python
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
count = 0
xor = x ^ y
while xor != 0:
xor &= (xor - 1)
count += 1
return count
Java
public class Solution {
public int hammingDistance(int x, int y) {
int count = 0;
int xor = x ^ y;
while (xor != 0) {
xor &= (xor - 1);
count++;
}
return count;
}
}
C++
class Solution {
public:
int hammingDistance(int x, int y) {
int count = 0;
int xorValue = x ^ y;
while (xorValue != 0) {
xorValue &= (xorValue - 1);
count++;
}
return count;
}
};