- 题目描述:给定一个int 数字,要求计算出int数字对应的二进制中1的个数。
1)利用左移或右移操作符
- 利用左移或者右移操作符,使1与该二进制数字的每一位进行按位与,结果若为1,则说明该位为1。
int countBit(int n) {
int count = 0;
for(int i=0; i<32; i++){
if(((n>>i)&1) == 1)
count++;
}
return count;
}
2)求余运算
- 该数每次都对2求余,若余数为1,则表示该位含有一个1,然后该数再除以2,重复上述步骤,直到该数为0。
int countBit(int n) {
int count = 0;
while(n){
if(n%2==1)
count++;
n = n/2;
}
return count;
}
3) n&(n-1)
- 让n与n-1按位与,该运算每次会去掉一个二进制位为1的那一位,直到n&(n-1)结果为0,所有二进制位数为1的都统计完了。
int countBit(int n) {
int count = 0;
while(n){
count++;
n = n&(n-1);
}
return count;
}