Bit Manipulation-计算一个整数中二进制中1的个数

来源:互联网 发布:一淘与淘宝联盟 编辑:程序博客网 时间:2024/05/21 10:53

整数n的二进制表示中1的个数:

n右移一位,然后与1相与,如果结果为1,说明此位数为1,以此类推,可得结果。

public static int count1BitNumber(int n){

int count = 0;
while(n != 0){
n>>=1;
count += n&1;
}
return count;
}
0 0