461. Hamming Distance

题目大意: 求两个数字的汉明距离,汉明距离是指两个数字对应位不同的数量,详情见示例

461. 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 ≤ x, y < 2^31.

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.

解题思路:通过异或运算^将对应位不同的数值标示出来,使用 Integer.bitCount() 方法返回二进制1的数量

public int hammingDistance(int x, int y) {
    return Integer.bitCount(x ^ y);
}

Last updated