位运算
191:位1的个数
public class Solution {
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
if((n&1) == 1){
count++;
}
n = n >>> 1;
}
return count;
}
}
递归:
public class Solution {
public int hammingWeight(int n) {
return weight(n);
}
public int weight(int n){
if(n == 0) return 0;
int count = n&1;
return count + weight(n>>>1);
}
}
- 汉明距离
class Solution {
//1.根据x,y按位异或
public int hammingDistance(int x, int y) {
int count = 0;
while(x != 0 || y != 0){
if(((x & 1)^(y & 1))==1) count++;
x = x>>>1;
y = y>>>1;
}
return count;
}
}
class Solution {
//2.根据x先异或,再x计算1个数(191题)
public int hammingDistance(int x, int y) {
int count = 0;
x = x^y;
while(x != 0){
if(((x & 1)&1)==1) count++;
x = x>>>1;
}
return count;
}
}
- Total Hamming Distance
本文探讨了位运算在计算位1个数(191题)的方法,以及如何用位运算实现汉明距离的计算。通过递归和迭代两种方式展示了如何利用位操作简化代码。重点在于理解位运算在算法中的应用和汉明距离在信息安全中的作用。
1021

被折叠的 条评论
为什么被折叠?



