Function to count set bits

 ways to count set bits of a number through programming:

 int setBits(int N) {

        int count = 0;

        int x = 1;

        while(x <= N)

        {

            if(x & N )

             count++;

            x = x << 1;

        }

        return count;

    }



another way to count set bits : 


int setBits(int n) {
       // Write Your Code here
       int c=0;
       while(n){
           int rsbm=n&(-n);
           n=n-rsbm;
           c++;
       }
       return c;
   }

Comments

Post a Comment