您的位置:首页 > 编程语言 > C语言/C++

[LeetCode]461. Hamming Distance(汉明距离)

2017-02-21 00:38 417 查看

LeetCode 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次方.

示例:

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.

代码如下:

class Solution {
public:
int hammingDistance(int x, int y) {
int c=0;
for(int i=0;i<31;i++)
{
if(x==0 && y==0)
break;
if(x%2 != y%2)
c++;
y=y/2;
x=x/2;
}
return c;
}
};


汉明距离(Hamming Distance)

汉明距离是以理查德·卫斯里·汉明的名字命名的。在信息论中,两个等长字符串之间的汉明距离是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。例如:

1011101 与 1001001 之间的汉明距离是 2。

2143896 与 2233796 之间的汉明距离是 3。

“toned” 与 “roses” 之间的汉明距离是 3。

摘选自百度百科
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C++