Count set bit in a integer (aka) number | interview question

In this tutorial we shall check how many number of bits set in a number with a simple logic.

Program:

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

Let us try to understand the above function with example 

Consider the num as 38

num = 38(100110) & 37(100101)  => num = 36(100100)  =>  count = 1
num = 36(100100) & 35(100011)  => num = 32(100000)  =>  count = 2
num = 32(100000) & 31(011111)  => num = 0  =>  count = 3

The logic is when a number is and with the previous number (number - 1) it will eliminate (clear) the last bit set in that number. With the help of this we can count the number of bits set in that number.