int main()
{
int c, i=10;
while(i)
{
i=i&(i-1);
c++;
}
printf("no, of ones in number 10 is %d\n", c);
}
Anonymous
Feb 15, 2019
while(i)
{
if(i & 1)
count++;
i >>= 1;
}
cout << i << endl;
Anonymous
Jan 10, 2020
So the best solution for this problem is to perform the bitwise and operation between number and number-1, every time you do this will take off the right most set bit. number of time this loops goes will give the number of bits set in the number
ex:
int count_set_bits(int number)
{
int count=0;
while(number)
{
count++;
number = number & (number - 1);
}
return count;
}