一、题目描述
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.
思路:先求出x异或y的值num,然后求出num的二进制中1的个数即是x和y的汉明距离
AC代码(c++版本):
class Solution {
public:
int hammingDistance(int x, int y) {
int num = x ^ y;
int count=0;
while(num){
count++;
num = num & (num-1);
}
return count;
}
};
go语言版本
func hammingDistance(x int, y int) int {
z := x^y
count := 0
m := 0
for z!= 0{
m = z%2
if m == 1{
count++
}
z = z/2
}
return count
}