#include "stdio.h"
#include "stdlib.h"
#include "iostream"
using namespace std;
int main(){
int a=5;
int i=0;
while(a!=0)
{
a=a&(a-1);
i++;
}
cout<<i<<endl;
system("pause");
return 0;
}
原理:
以7为例
7 1 1 1
& 1 1 0
6 1 1 0
& 1 0 0
5 1 0 1
& 1 0 0
4 1 0 0
& 0 0 0
3 0 1 0
三次与运算的结果不为0,7的二进制当中有3个1
利用每次减1后与原数的二进制有一位或两位变化的原理(减或借位),1-1=0,10-1=01