/**
* Input: x = 1, y = 4
* Output: 2
* Explanation:
* 1 (0 0 0 1)
* 4 (0 1 0 0)
* ↑ ↑
* @author yfmei
*
*/
public class HammingDistance {
public int hammingDistance(int x, int y) {
//String tr = Integer.toBinaryString(x);
//二进制转换
String xStr = toBinary(x);
String yStr = toBinary(y);
System.out.println("xStr.length:"+xStr.length()+" yStr.length:"+yStr.length());
//位数是否相同
int diff = getdiff(xStr, yStr);
if(diff > 0){//x比y大,y从左边开始补0
yStr = completeBinary(diff,yStr);
}else{//x比y小,x从左边开始补0
xStr = completeBinary(-diff,xStr);
}
System.out.println("xStr.length:"+xStr.length()+" yStr.length:"+yStr.length());
int num = xStr.length();
int distance = 0;
for(int i = 0;i < num;i++){
if(xStr.charAt(i) != yStr.charAt(i)){
distance = distance+1;
}
}
return distance;
}
public String toBinary(int x) {
String xStr = "" ;
while(x > 0){
xStr = ((x %2 == 0?"0":"1")+xStr);
x = x / 2;
}
return xStr;
}
/**
* 获取位数差
* @param xStr
* @param yStr
* @return
*/
public int getdiff(String xStr,String yStr) {
return xStr.length() -yStr.length();
}
/**
* 补足位数
* @param diff
* @param str
* @return
*/
public String completeBinary(int diff,String str) {
for(int i = 0;i < diff;i++){
str = "0"+str;
}
return str;
}
public static void main(String[] args) {
HammingDistance hammingDistance = new HammingDistance();
int distance = hammingDistance.hammingDistance(680142203, 1111953568);
System.out.println(distance);
//java提供的计算汉明间距的方法
System.out.println(Integer.bitCount(680142203 ^ 1111953568));
}
}
网友评论