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的问题。
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x ^ y;
int dist = 0;
while (z > 0) {
if (z & 1) dist++;
z >>= 1;
}
return dist;
}
};