题目的要求是得出两个整数的二进制表示下对应位数上的不同数字的位数。
下方是官网给出的范例,可以帮助理解。
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.
这个题目要解出来很简单,只需要知道异或这个概念就行了:两个数(二进制)值相同得0,不相同得1。
因此只要设一个变量result = x ^ y
,再去数result表示为二进制时1的个数就行了。代码如下
public class Solution {
public int hammingDistance(int x, int y) {
String temp = Integer.toBinaryString(x ^ y);
int count = 0;
char[] tempArray = temp.toCharArray();
for (int i = 0; i < temp.length(); i++) {
if (tempArray[i] == '1') {
count += 1;
}
}
return count;
}
}
Top Solution里还提到了Java代码库里面已经有内置的函数Integer.bitCount(x)
来统计一个整数二进制表示下1的个数,所以此题还可以简化成return Integer.bitCount( x ^ y);
。还一种不同的思路来计算一个数(二进制表示时)1的个数,通过每次右移再与1与依次检验每一位上是否为1
int result = x ^ y;
int count = 0;
for (int i = 0; i < 32; i++) {
count += (result >> i) & 1;
}
return count;