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 indirection in c?

815


Why enum is used in c?

711


What are types of preprocessor in c?

821


How can you tell whether a program was compiled using c versus c++?

847


What are the preprocessor categories?

836


What is 02d in c?

847


Why shouldn’t I start variable names with underscores?

851


what are bit fields? What is the use of bit fields in a structure declaration?

1783


What is the code for 3 questions and answer check in VisualBasic.Net?

1921


Add Two Numbers Without Using the Addition Operator

572


How many types of operators are there in c?

818


What is the difference between exit() and _exit() function in c?

850


Can a function argument have default value?

916


Should I learn data structures in c or python?

772


how do you programme Carrier Sense Multiple Access

1737