Search code examples
cbit-manipulationbitbitwise-operatorsbitwise-and

Counting number of one's in a binay number


how does this code works

for example

input: 5(101)
ouput: 2

the function is

scanf("%d", &a);
while(a)
{
oneina++;
a=a&(a-1);
}
printf("%d", oneina);

Solution

  • a-1 is a with the first 1 (from right) occurring in a as 0 and all the bits to the right of that bit as 1. So when you bitwise and them, you remove one 1 from a at a time.