0461. Hamming Distance (E)

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.

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;
    }
}
posted @ 2020-07-06 01:53  墨云黑  阅读(166)  评论(0编辑  收藏  举报