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 public, protected, private in c++?

640


What is a class template?

575


How can you quickly find the number of elements stored in a static array?

625


What is the difference between global int and static int declaration?

396


Explain dangling pointer.

671






What is long in c++?

726


Explain register storage specifier.

582


Define friend function.

558


Explain polymorphism?

572


Define vptr.

585


What are the uses of static class data?

626


Should you pass exceptions by value or by reference?

685


Can we declare a base-class destructor as virtual?

577


What is an operator in c++?

596


Can we change the basic meaning of an operator in c++?

645