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.Code:
public class Solution {
public int hammingDistance(int x, int y) {
int z=0;
int a=x^y;
String b=Integer.toBinaryString(a);
char[] bbb=b.toCharArray();
for(int i=0;i<bbb.length;i++){
if('1'==bbb[i])
z=z+1;
}
return z;
}
}
第一遍提交的时候遇到的问题是 画蛇添足地先把x、y转为二进制,然后转回int类型进行异或。但是二进制的是字符串 很长,再转回去导致溢出。所以failed。
XOR也就是异或 英文为exclusive OR。
第二种:
String b=Integer.toBinaryString(x^y);
b=b.replaceAll("0","");
return b.length();
但是运算时间更慢了。-= =
同时,发现不管什么进制,进行异或的时候都是二进制来异或然后显示成这个。
以及文中答案中的一个新的方法:
Integer.bitCount(x ^ y);
一行就可以完美解决本问题。