461 汉明距离

两个整数之间的汉明距离指的是这两个数字对应二进制位不一样的位置的数目。java

给出两个整数 x 和 y,计算它们之间的汉明距离。网络

注意:
0 ≤ x, y < 231.spa

示例:code

输入: x = 1, y = 4leetcode

输出: 2it

解释:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑io

上面的箭头指出了对应二进制位不一样的位置。class

来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/hamming-distance
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。二进制

 

题解:方法

java Integer的位与运算方法:

class  Solution {
     public   int  hammingDistance( int  x,  int  y) {
         return  Integer.bitCount(x^y);
    }
}
 
 
 
题解2:
class  Solution {
     public   int  hammingDistance( int  x,  int  y) {
         int  cnt= 0 ;
         while (x!= 0 ||y!= 0 ){
             if ((y& 1 )!=(x& 1 ))
            cnt++;
            x>>= 1 ;
            y>>= 1 ;
        }
         return  cnt;
    }
}