Another very common question is to count number of set bits in a given number.
Solution in C#
Solution in C#
int Count(int Number)
{
int count = 0;
while (Number != 0)
{
count += (Number & 1);
Number >>= 1;
}
return count;
}
int Count(int x)
{
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
return(x & 0x0000003f);
}