首先是复习时间
· C语言位操作:
& 位逻辑与
| 位逻辑或
^ 位逻辑异或
~ 位逻辑反
>> 右移
<< 左移
~ 位逻辑反
>> 右移
<< 左移
· GCC有一个叫做__builtin_popcount的内建函数,它可以精确的计算1的个数。因为用Dev C++作为IDE所以可以直接用。
题目如下:
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.
#include<iostream>
using namespace std;
int hammingDistance(int x, int y) {
return __builtin_popcount(x ^ y);//x xor y中1的个数 gcc的内建函数
}
int main()
{
int x, y;
cout << "x = ";
cin >> x;
cout << "y = ";
cin >> y;
cout << hammingDistance(x, y);
return 0;
}