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.
方法一:
class Solution {
public int hammingDistance(int x, int y) {
int [] Numx = new int[32];
int [] Numy = new int[32];
int t1=0;
int t2=0;
while(x>0){
Numx[31-t1] = x%2;
x = x/2;
t1++;
}
while(y>0){
Numy[31-t2] =y%2;
y = y/2;
t2++;
}
int total = 0;
for(int i =0;i<32;i++){
if(Numx[i]!=Numy[i]){
total++;
}
}
return total;
}
}
方法一:通过时间:14ms
思路:首先要理解数字是怎么转换成数组的
十进制转二进制(整数部分)
方法:用2辗转相除直到结果为1,将余数和最后的1从下向上的组合,就是我们想要的结果.
例如:60
60/2 = 30 余 0
30/2 = 15 余 0
15/2 = 7 余 1
7/2 = 3 余 1
3/2 = 1 余 1
1/2 = 0 余 1
所以十进制数60转为二进制数即为 111100
2)每个数转换成二进制的个数都不一样,所以规定一个length为32的数组,第一个数0在下标31中,第二个数0在下标30中,第三个数1在下标29中,以此类推。
3)记得先取余再除以2。
4)最后遍历两个长度为32的数组,每个比较就可以了。