How to count set bits in a number

First version:

  int CoutSetBits(int Num) {

  for (int count = 0; Num; Num >>= 1) {
    if (Num & 1)
      count++;
  }
  return count;
}

Optimized version:

  int CoutSetBits(int Num) {

  for (int count = 0; Num; count++) {
    Num &= Num - 1;
  }
}
Chitra
Chitra

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in