Bird
Raised Fist0
DSA C++programming

Count Set Bits Brian Kernighan Algorithm in DSA C++

Choose your learning style10 modes available
Mental Model
Count how many 1s are in a number's binary form by removing the rightmost 1 one at a time.
Analogy: Imagine you have a box of lit candles (1s). Each time you blow out the rightmost lit candle, you count one until none are left.
Number: 13 (binary 1101)
Bits: 1 1 0 1
          ↑
Rightmost 1 bit to remove
Dry Run Walkthrough
Input: number = 13 (binary 1101)
Goal: Count how many bits are set to 1 in the number 13
Step 1: Remove rightmost set bit from 1101
1101 (13) -> 1100 (12)
Why: Removing rightmost 1 reduces count by one and moves closer to zero
Step 2: Remove rightmost set bit from 1100
1100 (12) -> 1000 (8)
Why: Next rightmost 1 removed to count another set bit
Step 3: Remove rightmost set bit from 1000
1000 (8) -> 0000 (0)
Why: Last set bit removed, no more 1s left
Result:
0000 (0) with count = 3 set bits
Annotated Code
DSA C++
#include <iostream>
using namespace std;

// Function to count set bits using Brian Kernighan's Algorithm
int countSetBits(int n) {
    int count = 0;
    while (n > 0) {
        n = n & (n - 1); // remove rightmost set bit
        count++;        // increment count for each removal
    }
    return count;
}

int main() {
    int number = 13; // input number
    int result = countSetBits(number);
    cout << "Number of set bits in " << number << " is " << result << "\n";
    return 0;
}
while (n > 0) {
loop until all set bits are removed
n = n & (n - 1);
remove rightmost set bit to reduce number of 1s
count++;
count each removed set bit
OutputSuccess
Number of set bits in 13 is 3
Complexity Analysis
Time: O(k) because it loops only as many times as there are set bits (k) in the number
Space: O(1) because it uses a fixed amount of memory regardless of input size
vs Alternative: Compared to checking each bit one by one (O(log n)), this is faster when number has few set bits
Edge Cases
number = 0 (no set bits)
loop does not run, count remains 0
DSA C++
while (n > 0) {
number = 1 (single set bit)
loop runs once, count becomes 1
DSA C++
while (n > 0) {
number with all bits set (e.g. 15 for 4 bits)
loop runs equal to number of bits set, counting all
DSA C++
while (n > 0) {
When to Use This Pattern
When you need to count how many bits are 1 in a number efficiently, use Brian Kernighan's algorithm because it skips zero bits quickly.
Common Mistakes
Mistake: Using n & 1 and shifting right to count bits one by one
Fix: Use n = n & (n - 1) to remove rightmost set bit for faster counting
Summary
Counts how many bits are set to 1 in a number by removing the rightmost set bit repeatedly.
Use when you want a fast way to count set bits without checking every bit.
The key insight is that n & (n - 1) removes the rightmost 1 bit, reducing the problem size each step.

Practice

(1/5)
1. What does the Brian Kernighan algorithm do when counting set bits in an integer?
easy
A. It repeatedly clears the least significant set bit until the number becomes zero.
B. It counts the total number of digits in the integer.
C. It shifts the bits to the right one by one and counts all bits.
D. It converts the number to a string and counts '1' characters.

Solution

  1. Step 1: Understand the algorithm's main operation

    The Brian Kernighan algorithm works by clearing the least significant set bit in each iteration.
  2. Step 2: Effect of clearing bits

    Each clearing reduces the number of set bits by one until the number becomes zero.
  3. Final Answer:

    It repeatedly clears the least significant set bit until the number becomes zero. -> Option A
  4. Quick Check:

    Clearing bits one by one counts set bits [OK]
Hint: Clear least significant set bit repeatedly to count bits [OK]
Common Mistakes:
  • Counting all bits instead of only set bits
  • Using string conversion unnecessarily
  • Shifting bits without checking if set
2. Which of the following is the correct syntax for the main loop in Brian Kernighan's algorithm in C++?
easy
A. while (n > 0) { count += n % 2; n /= 2; }
B. for (int i = 0; i < n; i++) { count += n & 1; n >>= 1; }
C. while (n != 0) { n = n & (n - 1); count++; }
D. for (int i = 0; i < 32; i++) { count += (n >> i) & 1; }

Solution

  1. Step 1: Identify Brian Kernighan's loop

    The algorithm uses while (n != 0) and clears the least significant set bit by n = n & (n - 1).
  2. Step 2: Confirm increment of count

    Each iteration increments count by one for each cleared set bit.
  3. Final Answer:

    while (n != 0) { n = n & (n - 1); count++; } -> Option C
  4. Quick Check:

    Loop clears bits and counts [OK]
Hint: Use while with n = n & (n-1) to clear bits [OK]
Common Mistakes:
  • Using for loop instead of while
  • Counting bits by shifting instead of clearing
  • Using modulo instead of bitwise operations
3. What is the output of the following C++ code snippet using Brian Kernighan's algorithm?
int countSetBits(int n) {
  int count = 0;
  while (n) {
    n = n & (n - 1);
    count++;
  }
  return count;
}

int main() {
  int x = 13;
  std::cout << countSetBits(x);
  return 0;
}
medium
A. 5
B. 3
C. 2
D. 4

Solution

  1. Step 1: Convert 13 to binary

    13 in binary is 1101, which has three set bits (1s).
  2. Step 2: Apply Brian Kernighan's algorithm

    Each iteration clears one set bit, so count increments 3 times before n becomes 0.
  3. Final Answer:

    3 -> Option B
  4. Quick Check:

    Number of 1s in 1101 = 3 [OK]
Hint: Count 1s in binary of number for quick answer [OK]
Common Mistakes:
  • Counting total bits instead of set bits
  • Miscounting binary 1s
  • Confusing bitwise AND with OR
4. Identify the error in this Brian Kernighan algorithm implementation:
int countSetBits(int n) {
  int count = 0;
  while (n > 0) {
    n = n & (n + 1);
    count++;
  }
  return count;
}
medium
A. Missing return statement.
B. Not initializing count to zero.
C. Using while (n > 0) instead of while (n != 0).
D. Using n + 1 instead of n - 1 in bit clearing step.

Solution

  1. Step 1: Check bit clearing operation

    The correct operation to clear the least significant set bit is n = n & (n - 1), not n + 1.
  2. Step 2: Effect of wrong operation

    Using n + 1 does not clear bits properly and causes incorrect count or infinite loop.
  3. Final Answer:

    Using n + 1 instead of n - 1 in bit clearing step. -> Option D
  4. Quick Check:

    Correct bit clearing uses n & (n - 1) [OK]
Hint: Use n & (n - 1) to clear bits, not n + 1 [OK]
Common Mistakes:
  • Replacing n - 1 with n + 1
  • Confusing loop condition syntax
  • Forgetting to increment count
5. Given an array of integers, how can you use Brian Kernighan's algorithm to find the total number of set bits in all elements? Choose the best approach.
hard
A. Iterate over each element, apply Brian Kernighan's algorithm to count set bits, and sum all counts.
B. Convert all integers to strings and count '1's in each string, then sum.
C. Use a single Brian Kernighan's algorithm call on the sum of all integers.
D. Count set bits only in the first element and multiply by array size.

Solution

  1. Step 1: Understand counting set bits per element

    Brian Kernighan's algorithm counts set bits in one integer at a time.
  2. Step 2: Apply algorithm to each array element

    Iterate through the array, count set bits for each element, and sum these counts for total.
  3. Final Answer:

    Iterate over each element, apply Brian Kernighan's algorithm to count set bits, and sum all counts. -> Option A
  4. Quick Check:

    Sum of individual counts gives total set bits [OK]
Hint: Count bits per element, then sum for total [OK]
Common Mistakes:
  • Counting bits of sum instead of each element
  • Using string conversion unnecessarily
  • Assuming uniform bit count per element
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard