声明:原题目转载自LeetCode,解答部分为原创
Problem :
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.
思路 : 好久没做C++编程题了,先来道简单的练练手。对二进制表示数来说,汉明距离是指两个二进制数在对应位上的数不同(即对应
位置上,二进制数x、y的数分别为1、0)的位数之和。例如,对于(101) 和(000),第一位和第三位不同,则汉明距离为2。
计算两个二进制数的异或,记为z,转换为二进制数,记录位上数值为1的位数之和并输出。
代码如下:
#include
using namespace std;
int num_of_bits[35] = {0};
class Solution {
public:
int hammingDistance(int x, int y) {
// int num_of_bits[35] = {0};
int exclusive_or = x ^ y;
int index = 31;
while(exclusive_or != 0)
{
int temp = exclusive_or / 2;
int leave = exclusive_or - temp * 2;
num_of_bits[index --] = leave;
exclusive_or = temp;
}
int num = 0;
for(int i = index; i < 32 ; i ++)
{
if(num_of_bits[i])
num ++;
}
return num;
}
};
int main(){
Solution text_1;
int x, y;
cout << "Please input the text number (x, y) :" << endl;
cin >> x >> y;
cout << "The Hamming Distance of (1, 4) is :"<< endl;
cout << text_1.hammingDistance(x, y) << endl;
return 0;
}