Monday, March 12, 2012

Calculate the Number of "1" in the Binary Form of a Positive Integer

Problem: Given a positive integer, count the number of "1" in its binary form. For example, the binary form of "7" is "111", so the number of "1" is 3.

Solution: There is an elegant solution with a complexity of O(k) where k is the number of "1". The code is as follow:

int cout_numof1(int n)
{
 
   int cnt = 0;

   while(n)
   {
      n = n & (n-1);
      cnt++;
   }
  
   return cnt;
}

1 comment:

  1. This function is called population count (popcnt) and it even has its own instruction in many instruction sets. Your implementation is usually suboptimal, even if there is no popcnt instruction in your instruction set.

    http://en.wikipedia.org/wiki/Hamming_weight

    ReplyDelete