461. Hamming Distance
题目
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.
分析
"corresponding bits are different"即"异或"运算,Java中"异或运算符"的符号为^
(例:a的值是15,转换成二进制为1111;b的值是2,转换成二进制为0010。则a^b的结果为1101,即13。)
此题可转化为:求x异或y的结果的二进制表达式中'1'的个数
解答
解法1:(我)遍历二进制字符串(12ms)
将x异或y的结果转化为二进制字符串,遍历所有字符,求'1'的个数
public class Solution {
public int hammingDistance(int x, int y){
String str = Integer.toBinaryString(x ^ y);//或Integer.toString(x ^ y , 2)
int count = 0;
for (int i = 0; i < str.length(); i++){
if (str.charAt(i) == '1'){
count++;
}
}
return count;
}
}
解法2:求二进制字符串差值(18ms)
将x异或y的结果转化为二进制字符串,将其中所有"1"替换为""(空字符串),求替换前后字符串长度差值
public class Solution {
public int hammingDistance(int x, int y){
String str = Integer.toBinaryString(x ^ y);//或Integer.toString(x ^ y , 2)
String str2 = str.replaceAll("1","");
return str.length() - str2.length();
}
}
###解法3:使用系统内置函数Integer.bitCount()(24ms) Integer.bitCount() 返回指定int值的二进制补码表示形式的1位的数量。例:Integer.bitCount(5) = 2,因为5的二进制补码表示为101,其中'1'的个数为2 ``` public class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } } ```
###解法4:位运算(>>, &)(11ms√) 计算xor & 1,若xor末位为1,结果为1;若xor末位为0,结果为0。将结果记入count。再将xor右移1位。重复上述过程,直到xor右移到尽头(xor == 0) 0101 ---> 010 ---> 01 ---> 0 ``` public class Solution { public int hammingDistance(int x, int y){ int xor = x ^ y; int count = 0; while (xor != 0){ count += xor & 1; xor >>= 1; } return count; } } ```