一、问题描述
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.
二、我的思路
首先想到用位运算。
先把x和y异或(^),记作xor,里面是1的表示x与y不同的位,是0的表示相同的位。然后统计这个数字的二进制里面有多少个1就行了~
统计的时候每次把xor和1做与(&)运算,加到count里。因为规定了它们的最大值,所以循环最多32次,统计32位的情况。
代码:
class Solution {
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int count = 0;
for(int i = 0; i < 32; i ++){
count += xor & 1;
xor = xor >> 1;
}
return count;
}
}
1. 用我没见过的函数……
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
2. 方法类似,短小精悍。。
public int hammingDistance(int x, int y) {
int xor = x ^ y, count = 0;
for (int i=0;i<32;i++) count += (xor >> i) & 1;
return count;
}
3. 这个有点高端的样子
class Solution {
public:
int hammingDistance(int x, int y) {
int dist = 0, n = x ^ y;
while (n) {
++dist;
n &= n - 1;
}
return dist;
}
};
看不懂啊,这是什么…引用大神的解答:
@jonvasquez1 Considering this example. Let's say n = 10101
, and dist = 0
asccording to above code of @pengr7.
- Before we go into the
while
loop.n = 10101, dist = 0
- Loop 1.
dist = 1, n =10101 & 10100 = 10100
- Loop 2.
dist = 2, n =10100 & 10011 = 10000
- Loop 3.
dist = 3, n =10000 & (0)1111 = 0
- Loop ends.
dist = 3
The change of n
:
10101
10100
10000
00000
Conclusion: n & (n-1)
converts the right most 1
to 0
.
This is the key idea solving the problem. By counting how many times we can perform this operation, we know how many 1
exists in the binary representation of n
四、知识点
位运算。
参考博客:http://blog.csdn.net/xiaochunyong/article/details/7748713
五、碎碎念
对Java的位运算符不是特别熟悉。。继续加油~