count set bits in a number in cpp 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: count bits c++
//Method 1
int count = 0;
while (n)
{
count++;
n >>= 1;
}
//Method 2
int count = (int)log2(number)+1;