Bird
Raised Fist0
DSA Javaprogramming

Count Set Bits Brian Kernighan Algorithm in DSA Java

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 by one.
Analogy: Imagine erasing the rightmost lit candle on a birthday cake one at a time until none are left, counting how many you erased.
Number bits: 1 0 1 1 0 1 0 0
Rightmost 1 ->          ↑
Dry Run Walkthrough
Input: number = 13 (binary 1101)
Goal: Count how many bits are set to 1 in the binary form of 13
Step 1: Remove rightmost set bit from 1101 (13)
1101 (13) -> 1100 (12)
Why: Clearing the rightmost 1 reduces the count by one
Step 2: Remove rightmost set bit from 1100 (12)
1100 (12) -> 1000 (8)
Why: Next rightmost 1 is cleared
Step 3: Remove rightmost set bit from 1000 (8)
1000 (8) -> 0000 (0)
Why: Last set bit cleared, no more 1s left
Result:
0000 (0) -> count = 3
Annotated Code
DSA Java
public class CountSetBits {
    // Function to count set bits using Brian Kernighan's Algorithm
    public static 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;
    }

    public static void main(String[] args) {
        int number = 13; // binary 1101
        int result = countSetBits(number);
        System.out.println("Number of set bits in " + number + " is: " + result);
    }
}
while (n > 0) {
loop until all set bits are removed
n = n & (n - 1);
remove rightmost set bit by bitwise AND with n-1
count++;
increment count for 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 in the number
Space: O(1) because it uses a fixed amount of extra memory regardless of input size
vs Alternative: Compared to checking each bit one by one (O(log n)), this is faster when number of set bits k is small
Edge Cases
number = 0 (no set bits)
loop does not run, count remains 0
DSA Java
while (n > 0) {
number = 1 (single set bit)
loop runs once, count becomes 1
DSA Java
while (n > 0) {
number with all bits set (e.g., 15 for 4 bits)
loop runs equal to number of bits, counting all set bits
DSA Java
while (n > 0) {
When to Use This Pattern
When asked to count how many bits are 1 in a number efficiently, use Brian Kernighan's Algorithm because it skips zero bits and counts only set bits.
Common Mistakes
Mistake: Looping through all bits by shifting and checking each bit instead of using n & (n-1)
Fix: Use n = n & (n - 1) to remove rightmost set bit directly for faster counting
Summary
Counts the number of 1 bits in a number by repeatedly removing the rightmost set bit.
Use when you need an efficient way to count set bits without checking every bit.
The key insight is that n & (n-1) clears the rightmost set 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 counts the total number of digits in the integer
B. It converts the number to binary string and counts '0's
C. It shifts the bits to the right without changing the number
D. It repeatedly clears the least significant set bit until the number becomes zero

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 D
  4. Quick Check:

    Clearing bits one by one counts set bits [OK]
Hint: Clear least set bit repeatedly to count set bits [OK]
Common Mistakes:
  • Counting total digits instead of set bits
  • Shifting bits without counting
  • Counting zeros instead of ones
2. Which of the following Java code snippets correctly implements the Brian Kernighan algorithm to count set bits?
easy
A. int count = 0; for(int i=0; i<32; i++) { if((n & (1 << i)) != 0) count++; }
B. int count = 0; while(n > 0) { n = n >> 1; count++; }
C. int count = 0; while(n > 0) { n = n & (n - 1); count++; }
D. int count = 0; while(n > 0) { n = n | (n - 1); count++; }

Solution

  1. Step 1: Identify the correct bit clearing operation

    The Brian Kernighan algorithm uses n = n & (n - 1) to clear the least significant set bit.
  2. Step 2: Verify the loop and count increment

    Loop runs while n > 0 and increments count each time a bit is cleared.
  3. Final Answer:

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

    Use n = n & (n - 1) to clear bits [OK]
Hint: Use n = n & (n - 1) inside loop to count bits [OK]
Common Mistakes:
  • Using right shift instead of bit clearing
  • Using bitwise OR instead of AND
  • Counting bits by checking each bit manually
3. What is the output of the following Java code snippet?
int n = 13; // binary 1101
int count = 0;
while (n > 0) {
  n = n & (n - 1);
  count++;
}
System.out.println(count);
medium
A. 2
B. 3
C. 4
D. 5

Solution

  1. Step 1: Convert 13 to binary and count set bits

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

    Each iteration clears one set bit: - Iteration 1: 1101 & 1100 = 1100 - Iteration 2: 1100 & 1011 = 1000 - Iteration 3: 1000 & 0111 = 0000 Loop runs 3 times, so count = 3.
  3. Final Answer:

    3 -> Option B
  4. Quick Check:

    Number of set bits in 13 = 3 [OK]
Hint: Count set bits in binary 1101 = 3 [OK]
Common Mistakes:
  • Counting total bits instead of set bits
  • Miscounting set bits in binary
  • Confusing bitwise AND with OR
4. Identify the error in the following Java code that attempts to count set bits using Brian Kernighan's algorithm:
int countSetBits(int n) {
  int count = 0;
  while (n != 0) {
    n = n & (n + 1);
    count++;
  }
  return count;
}
medium
A. Using n + 1 instead of n - 1 in bit clearing step
B. Incorrect loop condition should be n > 0
C. Missing initialization of count variable
D. Using bitwise OR instead of AND

Solution

  1. Step 1: Check the bit clearing operation

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

    Using n + 1 does not clear the least significant set bit and leads to incorrect counting or infinite loop.
  3. Final Answer:

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

    Use n & (n - 1) to clear bits [OK]
Hint: Always use n & (n - 1) to clear bits [OK]
Common Mistakes:
  • Using n + 1 instead of n - 1
  • Wrong loop condition causing infinite loop
  • Confusing AND with OR operators
5. Given an array of integers, which Java method correctly uses Brian Kernighan's algorithm to return the total count of set bits in all elements?
int totalSetBits(int[] arr) {
  int total = 0;
  for (int num : arr) {
    while (num > 0) {
      num = num & (num - 1);
      total++;
    }
  }
  return total;
}
What is the output of totalSetBits(new int[]{3, 5, 7})?
hard
A. 7
B. 6
C. 8
D. 5

Solution

  1. Step 1: Count set bits for each element

    3 (binary 11) has 2 set bits, 5 (binary 101) has 2 set bits, 7 (binary 111) has 3 set bits.
  2. Step 2: Sum all set bits

    Total = 2 + 2 + 3 = 7.
  3. Step 3: Verify code logic

    The code correctly counts set bits for each number and sums them in total.
  4. Final Answer:

    7 -> Option A
  5. Quick Check:

    Sum of set bits in 3,5,7 = 7 [OK]
Hint: Sum set bits of each number using Brian Kernighan [OK]
Common Mistakes:
  • Miscounting set bits in numbers
  • Adding counts incorrectly
  • Using wrong bit clearing logic
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