461. Hamming Distance

来源:互联网 发布:vscode 支持xp吗 编辑:程序博客网 时间:2024/05/17 07:32

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 = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ?   ?The above arrows point to positions where the corresponding bits are different.解题思路:1.C语言中,x & 1从命令的角度讲,是将x的每一bit(2进制中的1和0都占一个bit)与0001的每一bit做与运算."&"是"与运算"的意思,1&1=1,其他情况(1&0,0&1,0&0)都=0.从逻辑的角度来讲,这个命令就是取x的最左边一位.例如x是0011,x&1得到0001,如果x是0110,x&1得到0000. x ^= y
是个异或并赋值的操作符。属于位操作符。二者不同返回1,相同返回 0;意思是   x与y异或的结果存入 x。假如 x的二进制是 00000000 00000000 00000000 11111111; 或者更长y的二进制是  00000000 00000000 11111111 00001111;则 x^=y;之后  x 的二进制是 00000000 00000000 11111111 11110000;x >>= 1表示将n的二进制表示向右移动一位再赋值给n
  1. int hammingDistance(int x, int y) {  
  2.         int count=0; 
  3. while (x || y)
  4. {
  5. if ((x & 1) ^ (y & 1))
  6. {
  7. count++;
  8. x >>= 1;
  9. y >>= 1;}
  10. }     
  11.        return count;  
  12.     } 
2.Java解法
1 public int hammingDistance(int x, int y) {2     int xor = x ^ y, count = 0;3     for (int i=0;i<32;i++) count += (xor >> i) & 1;4     return count;5 }


原创粉丝点击