Count Bits of 1

Geeks


Description:

Count the number of 1s within a integer.

Example:



Idea:

More efficient!

   1  Initialize count: = 0
   2  If integer n is not zero
      (a) Do bitwise & with (n-1) and assign the value back to n
          n: = n&(n-1)
      (b) Increment count by 1
      (c) go to step 2
   3  Else return count

Code:

#include <iostream>

using namespace std;

int countOnes(int num){
    int count=0;
    while(num!=0){
        num = num&(num-1);
        count++;
    }
    return count;

results matching ""

    No results matching ""