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:

  1. We define a function called countSetBits that takes an integer num as its parameter and returns an integer as the count of set bits.

  2. We initialize a variable count to 0. This variable will keep track of the number of set bits in the input integer.

  3. We start a while loop that continues until num becomes 0. Inside the loop, we perform the following steps:

  4. We use the bitwise AND operator (&) to check if the least significant bit of num is set (i.e., equal to 1). If it is, we increment the count variable by 1.

  5. We right-shift num by 1 bit position using the >>= operator. This shifts all bits in num to the right by 1 position, effectively moving the next bit to be checked into the least significant bit position.

  6. The loop continues until all bits in num have been checked, and num becomes 0.

  7. 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.