What is the most efficient way to count the number of bits
which are set in a value?

Answer Posted / venkat1435

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)

Is This Answer Correct ?    31 Yes 6 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is union and structure in c?

624


Are pointers integers in c?

615


What is the right type to use for boolean values in c? Is there a standard type? Should I use #defines or enums for the true and false values?

610


Given an array of 1s and 0s arrange the 1s together and 0s together in a single scan of the array. Optimize the boundary conditions?

987


What does malloc () calloc () realloc () free () do?

565






What does void main return?

612


What do you mean by dynamic memory allocation in c? What functions are used?

662


Why c is called top down?

636


write a program that types this pattern: 12345678987654321 12345678 87654321 1234567 7654321 123456 654321 12345 54321 1234 4321 123 321 12 21 1 1

3300


What are c preprocessors?

681


Explain the use of #pragma exit?

703


What is scope rule of function in c?

556


What is the difference between functions getch() and getche()?

627


Explain what is a pragma?

596


Differentiate between ordinary variable and pointer in c.

625