/**
* 判断一个数中哟多少个1
* 使用移位,int为32位,通过移位判断
*/
public static int count1(int n){
int count = 0;
int i = 0;
do{
if((n&1) == 1){
count ++;
}
i ++;
n >>= 1;
}while (i<32);
return count;
}
/**
* 使用算法:如n=9 (二进制写法1001) ,则n-1=8 (二进制写法1000),
* 1001 & 1000 后结果为1000,即去掉了最右端的1,
* 1000 再& 0111 结果为0000,如此统计循环的次数即可
* @param n
* @return
*/
public static int countBits(int n) {
int count = 0;
while (n!=0){
n &= (n-1);
count ++ ;
}
return count;
}
public static void main(String[] args) {
int val = 58585858;
System.out.println(val+"包含1的数量为:"+count1(val));
System.out.println(val+"包含1的数量为:"+countBits(val));
}
n的二进制包含多少个1
最新推荐文章于 2025-11-27 12:57:54 发布
本文介绍了两种计算整数二进制表示中1的数量的方法。第一种方法使用位移操作,通过将整数右移并检查最低位是否为1来逐位计数。第二种方法采用一种更高效的算法,通过连续进行n&(n-1)操作直到n变为0,每次操作去掉最右边的1,从而减少循环次数。

8万+

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



