• Advertisement
Sign in to follow this  

counting no of set bits in number

This topic is 4338 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is the question Write a fast way to count the number of set bits in an unsigned int Here is my code-
#include <iostream>

int main()
{
	int count=0;
	unsigned int x=50;
	while(x>0)
		{
		if(x&1)
			{
			++count;
			}
		x>>=1;
		}
	std::cout<<count;
return 0;
}

Is it fast or is ther any other better way?

Share this post


Link to post
Share on other sites
Advertisement
How does the question define "fast"? As in productivity/maintainability, or as in bit twiddling?

#include <bitset>
#include <iostream>

int main()
{
std::bitset<32> foo;
foo.set(5);
foo.set(10);
std::cout << foo.count() << "\n";
}





Will output: 2

[Edited by - Will F on April 8, 2006 12:13:31 AM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement