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 < 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.

解题思路: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 }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值