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

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.

题意:求两个数x、y的二进制下各位不同的总数。
          用位运算^异或,每个位相同为0,不同则为1。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int res=0;
        int n = x^y;
        while(n)
        {
            res++;
            n=n&(n-1);
        }
        return res;
    }
};
/*直接模拟*/
class Solution {
public:
    int hammingDistance(int x, int y) {
        int res=0;
        int cnt_x=0,cnt_y=0;
        while(x&&y)
        {
            if(y%2!=x%2)res++;
            y/=2,x/=2;
        }
        while(x)
        {
            if(x%2) res++;
            x/=2;
        }
        while(y)
        {
            if(y%2) res++;
            y/=2;
        }
        return res;
    }
};

你可能感兴趣的:(算法编程题,leetcode)