Give a very good method to count the number of ones in a "n"
(e.g. 32) bit number.

Answer Posted / artyom

// It's still O(n), maybe there are better ways.
int countBit(int num)
{
int count = 0;
while(num)
{
count += static_cast<int>(static_cast<bool>(mask &
0x1));
num >>= 1;
}
return count;
}

Is This Answer Correct ?    2 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is functions syntax in c++?

713


What are the steps in the development cycle?

705


What is while loops?

708


What does iomanip mean in c++?

712


We all know that a const variable needs to be initialized at the time of declaration. Then how come the program given below runs properly even when we have not initialized p?

694






What does #define mean in c++?

762


Can java be faster than c++?

766


What is else if syntax?

772


What are containers in c++?

653


Comment on local and global scope of a variable.

671


Explain the differences between list x; & list x();.

684


What is the correct syntax for inheritance a) class aclass : public superclass b) class aclass inherit superclass c) class aclass <-superclass

790


What do you mean by const correctness?

717


Define a pointer to a data member of the type pointer to pointer?

662


What is a pointer with example?

756