Hamming Distance

来源:互联网 发布:开淘宝服装店进货渠道 编辑:程序博客网 时间:2024/06/06 07:18

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的个数

技巧
把整数减一后的值与原值按位与,相当于把整数二进制中最右边的一个1变成0

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

另外python中内置bin函数可以将整数转换为二进制字符串,然后用count函数统计字符串中1的个数也可以达到效果

#pythonclass Solution(object):    def hammingDistance(self, x, y):        """        :type x: int        :type y: int        :rtype: int        """        return bin(x^y).count('1')
原创粉丝点击