[LeetCode] 461. Hamming Distance(位操作)

传送门

Description

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.

思路

题意:给定两个数,求出其汉明距离

题解:将两个数异或,那么二进制位上相同的都变成0,不同变成1,统计一下有多少个1即可

 
class Solution {
public:
    //6ms
    int hammingDistance(int x, int y) {
        int res = 0;
        while (x && y){
            if ((x & 1) != (y & 1)) res++;
            x >>= 1;
            y >>= 1;
        }
        while (x){
            if (x & 1)	res++;
            x >>= 1;
        }
        while (y){
            if (y & 1)	res++;
            y >>= 1;
        }
        return res;
    }

    //3ms
    int hammingDistance(int x,int y){
        x ^= y;
        y = 0;
        while (x){
            y += (x & 1);
            x >>= 1;
        }
        return y;
    }
};

  

 
原文地址:https://www.cnblogs.com/ZhaoxiCheung/p/7363844.html