题目

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:

  1. Input: x = 1, y = 4
  2. Output: 2
  3. Explanation:
  4. 1 (0 0 0 1)
  5. 4 (0 1 0 0)
  6. The above arrows point to positions where the corresponding bits are different.

题意

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

思路

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


代码实现

Java

移位判断

  1. class Solution {
  2. public int hammingDistance(int x, int y) {
  3. int distance = 0;
  4. while (x != 0 || y != 0) {
  5. if ((x & 1) != (y & 1)) {
  6. distance++;
  7. }
  8. x >>= 1;
  9. y >>= 1;
  10. }
  11. return distance;
  12. }
  13. }

异或

  1. class Solution {
  2. public int hammingDistance(int x, int y) {
  3. int distance = 0;
  4. int xor = x ^ y;
  5. while (xor != 0) {
  6. if ((xor & 1) == 1) distance++;
  7. xor >>= 1;
  8. }
  9. return distance;
  10. }
  11. }