int countSetBits(int n) { int count = 0; while (n) { n &= (n - 1); count++; } return count; } int main() { int x = 29; // binary 11101 std::cout << countSetBits(x); return 0; }
The binary representation of 29 is 11101, which has 4 set bits (1s). Brian Kernighan's algorithm counts these by repeatedly turning off the rightmost set bit until the number becomes zero.
n = n & (n - 1) do to the binary number n?Subtracting 1 from n flips the rightmost set bit and all bits after it. The AND operation with n clears that rightmost set bit, effectively removing one '1' from the binary representation.
int countSetBits(int n) { int count = 0; while (n > 0) { n = n & (n + 1); count++; } return count; }
The code uses n & (n + 1) instead of n & (n - 1). This does not clear the rightmost set bit and can cause n to never reach zero, leading to an infinite loop.
Option C correctly applies Brian Kernighan's algorithm to each number in the array, counting set bits by clearing the rightmost set bit until the number becomes zero.
Option C uses n & (n + 1), which is incorrect. Option C uses a built-in function, not the algorithm. Option C counts all bits, not just set bits.
Brian Kernighan's algorithm loops only once per set bit, skipping zero bits entirely, making it faster especially for numbers with few set bits.
