461. 汉明距离
题目:
461. 汉明距离
题解:
可以参考:
面试题15. 二进制中1的个数
代码:
public class code461 {
// // 方法一: 内置位计数功能
// public static int hammingDistance(int x, int y) {
// return Integer.bitCount(x ^ y);
// }
// // 方法二: 使用toBinaryString函数
// public static int hammingDistance(int x, int y) {
// String str = Integer.toBinaryString(x ^ y);
// char a[] = str.toCharArray();
// int res = 0;
// for(int i = 0; i < a.length; i++)
// {
// if(a[i] == '1')
// {
// res++;
// }
// }
// return res;
// }
// // 方法三: 逐位运算
// public static int hammingDistance(int x, int y) {
// int n = x ^ y;
// int res = 0;
// while(n != 0) // 必须是n!=0 而不能是n>0, 因为输入的可能是负数
// {
// res = res + (n & 1);
// n = n >>> 1;
// }
// return res;
// }
// 方法四: 巧用 n & (n - 1)
public static int hammingDistance(int x, int y) {
int n = x ^ y;
int res = 0;
while(n != 0) // 必须是n!=0 而不能是n>0, 因为输入的可能是负数
{
res = res + 1;
n = n & (n - 1);
}
return res;
}
public static void main(String[] args) {
int x = 1;
int y = 4;
int res = hammingDistance(x, y);
System.out.println(res);
}
}
参考:
- 汉明距离
- 按位异或—>判断二进制位中1的个数
- 一行轻松解决
还没有评论,来说两句吧...