461. Hamming Distance【数学|位运算】
2017/3/14 15:23:55
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.
题目要求:求两个数字二进制位中同一位置不同bit的个数。
解法1 Java 利用1的移位依次匹配是否对应位为1,统计为1的个数。
public class Solution {
public int hammingDistance(int x, int y) {
x ^= y;
int count = 0;
for ( int i=0;i<32;i++ )
count = (1<<i & x ) !=0 ? count+1 : count;
return count;
}
}
解法2 Java 利用 a &= a-1 依次去掉最后一个1,统计循环次数。
public class Solution {
public int hammingDistance(int x, int y) {
x ^= y;
int count = 0;
while( x != 0 ){
x &= x - 1;
count++;
}
return count;
}
}

浙公网安备 33010602011771号