Hamming Distance (E)

题目

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.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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.

题意

计算两个整数之间的汉明距离,即二进制对应位不相等的个数。

思路

可以直接移位判断,也可以异或后统计1的个数。

代码实现

Java

移位判断

class Solution {
    public int hammingDistance(int x, int y) {
        int distance = 0;

        while (x != 0 || y != 0) {
            if ((x & 1) != (y & 1)) {
                distance++;
            }
            x >>= 1;
            y >>= 1;
        }

        return distance;
    }
}

异或

class Solution {
    public int hammingDistance(int x, int y) {
        int distance = 0;
        int xor = x ^ y;

        while (xor != 0) {
            if ((xor & 1) == 1) distance++;
            xor >>= 1;
        }

        return distance;
    }
}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄