Question { 13575 }
What is the most efficient way to count the number of bits
which are set in a value?
Answer
main()
{
int n,count=0;
printf("enter a number");
scanf("%d",&n);//enterd no.is 5
while(n>0)
{
count++;
n=n&n-1;//binary of n is 101
// binary of n-1 is 100
//n&n-1 is (i.e 101
&100 =100 )
}
printf("%d",count);
getch();
} output is 2(i.e 2 ones in 101)