问题详见:Hamming Distance
这是在CSDN上的第一篇博客,开篇以C++的位操作的一个题目来打头阵。下面是问题描述:
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.
由描述可知,汉明距离(Hamming Distance)就是比较两个整数的二进制表示中,不同的位的总数。下面是AC的代码:
#include<iostream>
#include<iomanip>
#include<cmath>
#include<string>
#include<cstring>
#include<cstdlib>
#include<climits>
#include<vector>
using namespace std;
int main(){
int x,y;
cout<<"Please input two integers:"<<endl;
cin>>x>>y;
/*算法1
int a=x^y,answer=0;
while(a!=0){
answer++;
a&=a-1;
}
*/
//算法二
int answer=0;
while(x!=y){
answer+=(x&1)^(y&1);
x>>=1;
y>>=1;
}
cout<<"Those two integers'' Hamming Distance is:"<<answer<<endl;
return 0;
}算法一是将x和y异或操作之后计算其中二进制中1的个数,其计算的方法是通过自身和自身减一的二进制数逐位相与,然后减一之后继续循环直至为0,这样也就将其二进制中1的个数计算出来;
算法二是将x和y的最后一位异或操作然后将其都右移一位以后再次计算其异或操作的和,直至两个数相等。
从算法复杂度来看,两种算法的复杂度均为O(n)。
整体来看,虽然实现方法不同,但两个算法都是通过异或操作计算其汉明距离,这也主要是由于汉明距离的定义所致。
版权声明:本文为Poison520原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。