Skip to content

Latest commit

 

History

History
142 lines (108 loc) · 2.44 KB

File metadata and controls

142 lines (108 loc) · 2.44 KB

English Version

题目描述

两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

给出两个整数 xy,计算它们之间的汉明距离。

注意:
0 ≤ x, y < 231.

示例:

输入: x = 1, y = 4

输出: 2

解释:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

上面的箭头指出了对应二进制位不同的位置。

解法

利用异或运算的规律找出不同的位

  • 0 ^ 0 = 0
  • 1 ^ 1 = 0
  • 0 ^ 1 = 1
  • 1 ^ 0 = 1

Python3

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        num, count = x ^ y, 0
        while num != 0:
            num &= num - 1
            count += 1
        return count

Java

class Solution {
    public int hammingDistance(int x, int y) {
        int num = x ^ y;
        int count = 0;
        while (num != 0) {
            num &= num - 1;
            count++;
        }
        return count;
    }
}

或者利用库函数 Integer.bitCount()

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

JavaScript

/**
 * @param {number} x
 * @param {number} y
 * @return {number}
 */
var hammingDistance = function (x, y) {
    let distance = x ^ y;
    let count = 0;
    while (distance != 0) {
        count++;
        distance &= distance - 1;
    }
    return count;
};

C++

class Solution {
public:
    int hammingDistance(int x, int y) {
        x ^= y;
        int count = 0;
        while (x) {
            ++count;
            x &= (x - 1);
        }
        return count;
    }
};

Go

func hammingDistance(x int, y int) int {
	x ^= y
	count := 0
	for x != 0 {
		count++
		x &= (x - 1)
	}
	return count
}

...