Count Set Bits in An Integer
Count Set Bits in An Integer
getchar();
return 0;
}
1 Initialize count: = 0
2 If integer n is not zero
(a) Do bitwise & with (n-1) and assign the value back to n
n: = n&(n-1)
(b) Increment count by 1
(c) go to step 2
3 Else return count
#include<stdio.h>
int countSetBits(int n)
{
unsigned int count = 0;
while (n)
{
n &= (n-1); n = n & (n-1);
count++;
}
return count;
}
n = 9 (1001)
count = 0
3. Using Lookup table: We can count bits in O(1) time using lookup table.
Please see http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable
for details.