【leetcode】461. Hamming Distance

problem

461. Hamming Distance

solution1:

根据题意,所求汉明距离指的是两个数字的二进制对应位不同的个数。对应位异或操作为1的累积和。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int ans = 0;
        for(int i=0; i<32; i++)
        {
            if((x&(1<<i))^(y&(1<<i))) ans++;
        }
        return ans;
        
    }
};

solution2:

两个数字异或之后,统计结果二进制中1的个数。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int ans = 0;
        int tmp = x ^ y;
        for(int i=0; i<32; i++)
        {
            ans += ((tmp>>i) & 1);//err.
        }
        return ans;
        
    }
};

注意,两种solution都是移动 i 个位置。

参考

1. Leetcode_461. Hamming Distance;

原文地址:https://www.cnblogs.com/happyamyhope/p/10565470.html