count set bits c++ code example

Example 1: Count set bits in an integer c++

//Method 1
	int count = __builtin_popcount(num);
//Method 2
	int count = 0;
    while (num) {
        count += num & 1;
        n >>= 1;
    }

Example 2: bit counting

countBits = (n) => n.toString(2).split("0").join("").length;

Example 3: bitwise count total set bits

//WAP to find setbits (total 1's in binary ex. n= 5 => 101 => 2 setbits
int count{}, num{};
  cin >> num;

  while (num > 0) {
    count = count + (num & 1); // num&1 => it gives either 0 or 1
    num = num >> 1;	// bitwise rightshift 
  }

	 cout << count; //count is our total setbits

Example 4: count bits c++

//Method 1
   int count = 0;
   while (n)
   {
        count++;
        n >>= 1;
    }
//Method 2
	int count = (int)log2(number)+1;

Tags:

Misc Example