xxxxxxxxxx
#include <iostream>
// Function to count the total number of set bits in a number
int countSetBits(int n) {
int count = 0;
while (n != 0) {
// Increment count if the least significant bit is set (i.e., equal to 1)
count += n & 1;
// Right-shift the number by 1 to check the next bit
n >>= 1;
}
return count;
}
int main() {
int num = 123; // Replace 123 with the desired number
int setBits = countSetBits(num);
std::cout << "Total set bits in " << num << ": " << setBits << std::endl;
return 0;
}
xxxxxxxxxx
//Method 1
int count = __builtin_popcount(number);
//Method 2
int count = 0;
while (number) {
count += number & 1;
n >>= 1;
}
xxxxxxxxxx
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
xxxxxxxxxx
//Method 1
int count = 0;
while (n)
{
count++;
n >>= 1;
}
//Method 2
int count = (int)log2(number)+1;