描述
两个整数的Hamming距离是对应比特位不同的个数。
给定两个整数x和y,计算两者的Hamming距离。
0 ≤ x, y < 2^31.
您在真实的面试中是否遇到过这个题?
样例
输入: x = 1, y = 4
输出: 2
public class Solution {
/**
* @param x: an integer
* @param y: an integer
* @return: return an integer, denote the Hamming Distance between two integers
*/
public int hammingDistance(int x, int y) {
int diff = x ^ y;
return Integer.bitCount(diff);
}
}
public class Solution {
/**
* @param x: an integer
* @param y: an integer
* @return: return an integer, denote the Hamming Distance between two integers
*/
public int hammingDistance(int x, int y) {
// write your code here
int res = 0;
while(x!=0 || y!=0){
int remX = x % 2;
int remY = y % 2;
if((remX ^ remY) == 1){
res++;
}
x = x >> 1;
y = y >> 1;
}
return res;
}
}