How does this method count the number of 1s in binary representation?

Viewed 424

Possible Duplicate:
n & (n-1) what does this expression do?

Consider the following algorithm:

int count(int num)
{
  int ones = 0;
  while(num)
  {
    ++ones; 
    num &= num - 1;
  }

  return ones;
}

What is the significance of num & (num-1)? How does it work?

3 Answers
Related