Possible Duplicate:
Best algorithm to count the number of set bits in a 32-bit integer?
Given a 32-bit integer N,Devise an algorithm to find the number of zeros in the binary bit representation of N.
The simplest algorithm I can think of is to check the binary representation for Zeros,in C something like this:
int num_of_zero(int num)
{
if(0 == num) return 1; /*For the input 0 it should output 1 */
int Count = 0;
while(num>0){
if(0 == (num&1)) Count++;
num >>= 1;
}
return Count;
}
I was wandering if there is some algorithm to compute at constant time.
For input 0 it should return 1 not 32.
For 5 the output should be 1.As binary representation is 101.
For 7 the output should be 0.
Precisely,I am looking for a better algorithm to compute number of (non-leading) zeros in the binary interpretation of an 32 bit integer.Hope the problem is clear now.
Edit: As pointed Alex Martelli,delroth I am modifying my code to made it more readable & using iteration this time.