leetcode 461 hamming distance

题意

统计两个整数转换成二进制位时位数不同的个数。

题目来源:https://leetcode.com/problems/hamming-distance/

标记难度:Easy

提交次数:1/2 (少写了 return 语句。。)

代码效率:91.77%

分析

二进制的每一位的值不是 0 就是 1,就是整数除以 2 取余的结果,判断是否相等。然后再取模(相当于向左移动一位),再取余作比较。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class  {
public int hammingDistance(int x, int y) {
int count = 0;
int i = 0;
int j = 0;
while(x != 0 || y != 0){
i = x % 2;
j = y % 2;
if(i != j){
count++;
}
x = x / 2;
y = y / 2;
}
return count;
}
}

参考

别人的一行代码实现Orz:

1
2
3
4
5
public class  {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}