Count set bits in an integer c++
To count the number of set bits in an integer in C++, you can use the bitwise AND operator and a loop. Here's an example code snippet:
int countSetBits(int num) {
int count = 0;
while (num != 0) {
count += num & 1;
num >>= 1;
}
return count;
}
Let's break down the code and explain each step:
We define a function called
countSetBits
that takes an integernum
as its parameter and returns an integer as the count of set bits.We initialize a variable
count
to 0. This variable will keep track of the number of set bits in the input integer.We start a while loop that continues until
num
becomes 0. Inside the loop, we perform the following steps:We use the bitwise AND operator (
&
) to check if the least significant bit ofnum
is set (i.e., equal to 1). If it is, we increment thecount
variable by 1.We right-shift
num
by 1 bit position using the>>=
operator. This shifts all bits innum
to the right by 1 position, effectively moving the next bit to be checked into the least significant bit position.The loop continues until all bits in
num
have been checked, andnum
becomes 0.Finally, we return the count of set bits.
This algorithm works by checking each bit of the input integer starting from the least significant bit and counting the number of 1s encountered. The right-shift operation helps in moving to the next bit in each iteration.