解法一:
public class Solution {
public int hammingDistance(int x, int y) {
int count = 0;
String xs = Integer.toBinaryString(x);
String ys = Integer.toBinaryString(y);
int xl = xs.length() - 1;
int yl = ys.length() - 1;
while(xl >= 0 && yl >= 0){//倒着判断(从低位往高位,因为小的数可能高位不存在),题目中说了x,y都是非负数
if(xs.charAt(xl) != ys.charAt(yl)){
count++;
}
xl--;
yl--;
}
while(xl >= 0){
if(xs.charAt(xl) == '1'){//因为小的数高位补全后也为0,所以1才是不同的
count++;
}
xl--;
}
while(yl >= 0){
if(ys.charAt(yl) == '1'){
count++;
}
yl--;
}
return count;
}
}