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 ≤ xy < 231.

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.

用Java的位运算,
public class Solution {
    public int hammingDistance(int x, int y) {
        int sum=0;
         while(x>0 || y>0)
         {
             int x1=x & 1;// 位与:第一个操作数的的第n位于第二个操作数的第n位如果都是1,那么结果的第n为也为1
             int y1=y & 1;


                if((x1^y1)==1)// 第一个操作数的的第n位于第二个操作数的第n位 相反,那么结果的第n为也为1,否则为0
                    sum++;
                y=y>>1;  // 右移( >> ) 高位补符号位
                x=x>>1;
         }
        return sum ; 
    }
}
原文地址:https://www.cnblogs.com/sunli0205/p/6427544.html