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 a buffer in c?

800


What is the difference between c &c++?

882


Differentiate fundamental data types and derived data types in C.

842


What are the modifiers available in c programming language?

1017


What does typeof return in c?

874


What is self-referential structure in c programming?

929


Explain c preprocessor?

905


What is typeof in c?

796


What is the use of clrscr?

840


How many types of operators are there in c?

845


What is main () in c language?

876


How are strings stored in c?

816


Can we change the value of static variable in c?

795


What is keyword in c?

811


Explain what math functions are available for integers? For floating point?

878