Reputation: 85
int fn(unsigned int x)
{
int count = 0 ;
for(; x!=0; x&=(x-1))
count ++;
return count;
}
I tried it out in the complier but couldn't figure out what is happening. I think it's something to do with the number of bits the in x
, but what?
Upvotes: 2
Views: 163
Reputation: 17585
I explain what you have done :)
As per your code , following will happen if x = 5
1) In first iteration of loop,
a) condition check : .... 0101(X) ! = 0 ,
b) body : count will be 1 ;
c) increment part : .... 0101 &= .... 0100 => .... 0100
2) In second Itearation
a) condition check : .... 0100(X) ! = 0 ,
b) body : count will be 2 ;
c) increment part : .... 0100 &= .... 0011 => .... 0000
The count is equal to 2 which is number of bits set in X(5)
Upvotes: 0
Reputation: 63775
It's a bit trick. :)
You're returning the number of bits set to 1
.
Upvotes: 9