package others;
public class HammingWeight {
public static void main(String[] args) {
int n = -3;
int count = hammingWeight02(n);
System.out.println(count);
}
//思路1:循环和位移动
public static int hammingWeight(int n) {
int bits = 0;
int mask = 1;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0) {
bits++;
}
mask <<= 1;
}
return bits;
}
//思路2:观察思路1的结果就会发现,n & (n - 1) 就会把n 中最低位的1变为0
public static int hammingWeight02(int n) {
int bits = 0;
while (n != 0) {
bits ++;
n &= (n - 1);
}
return bits;
}
}
位1的个数的两种思路及JAVA代码
最新推荐文章于 2024-08-23 15:54:50 发布