题目
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:
Example
The above arrows point to positions where the corresponding bits are different.
解
class Solution {
public int hammingDistance(int x, int y) {
int h=0;
ArrayList<Integer> rx=new ArrayList<Integer>();
ArrayList<Integer> ry=new ArrayList<Integer>();
while(x/2!=0){
rx.add(x%2);
x=x/2;
}
if(x%2!=0) rx.add(x%2);
while(y/2!=0){
ry.add(y%2);
y=y/2;
}
if(y%2!=0) ry.add(y%2);
int sizeX=rx.size();
int sizeY=ry.size();
int i=0;
int j=0;
while(i<sizeX && j<sizeY){
Integer A=rx.get(i);
Integer B=ry.get(j);
if(!A.equals(B)){
h++;
}
i++;
j++;
}
if(i==sizeX){
while(j<sizeY){
if(ry.get(j).equals(1)){
h++;
}
j++;
}
}else{
while(i<sizeX){
if(rx.get(i).equals(1)){
h++;
}
i++;
}
}
return h;
}
}
更简单的解法
//解法1
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
//解法2
public class Solution {
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;
}
}