Bird
Raised Fist0
DSA Javascriptprogramming

Count Set Bits Brian Kernighan Algorithm in DSA Javascript

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 you have a pile of coins and you keep taking away the top coin until none are left. Each coin taken is like a 1 bit removed.
Number in binary:  1 0 1 1 0 1 0 0
Bits:               ↑           ↑
Rightmost 1 bit:                ↑
Dry Run Walkthrough
Input: number = 13 (binary 1101)
Goal: Count how many bits are set to 1 in the number 13
Step 1: Start with number = 13 (binary 1101), count = 0
1101 (13) ↑ count=0
Why: Initialize count and start with the original number
Step 2: Remove rightmost set bit: number = number & (number - 1) -> 1101 & 1100 = 1100 (12), count = 1
1100 (12) ↑ count=1
Why: Removing rightmost 1 bit reduces number and increases count
Step 3: Remove rightmost set bit again: number = 1100 & 1011 = 1000 (8), count = 2
1000 (8) ↑ count=2
Why: Keep removing rightmost 1 bits to count all set bits
Step 4: Remove rightmost set bit again: number = 1000 & 0111 = 0000 (0), count = 3
0000 (0) ↑ count=3
Why: When number becomes zero, all set bits are counted
Result:
0000 (0) ↑ count=3
Answer: 3 set bits in 13
Annotated Code
DSA Javascript
class BitCounter {
  static countSetBits(n) {
    let count = 0;
    while (n !== 0) {
      n = n & (n - 1); // remove rightmost set bit
      count++; // increment count for each removed bit
    }
    return count;
  }
}

// Driver code
const number = 13;
const result = BitCounter.countSetBits(number);
console.log(`${result} set bits in ${number}`);
while (n !== 0) {
loop until all set bits are removed
n = n & (n - 1); // remove rightmost set bit
remove the rightmost 1 bit from n
count++; // increment count for each removed bit
count how many bits have been removed
OutputSuccess
3 set bits in 13
Complexity Analysis
Time: O(k) where k is the number of set bits because each iteration removes one set bit
Space: O(1) because only a few variables are used regardless of input size
vs Alternative: Compared to checking every bit (O(log n)), this is faster when number has fewer set bits
Edge Cases
number = 0 (no set bits)
loop does not run, count remains 0
DSA Javascript
while (n !== 0) {
number with all bits set (e.g., 7 for 3 bits)
loop runs for all bits, count equals total bits set
DSA Javascript
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: Looping through all bits by shifting without using n & (n-1)
Fix: Use n = n & (n - 1) to remove rightmost set bit directly for faster counting
Summary
Counts how many bits are set to 1 in a number using a fast bit removal trick.
Use when you want to count set bits efficiently without checking every bit.
The key insight is that n & (n-1) removes the rightmost set bit, reducing work each step.

Practice

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

Solution

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

    The algorithm clears the least significant set bit by doing n = n & (n-1) repeatedly.
  2. Step 2: Effect of clearing bits

    Each operation removes one set bit, counting how many times this happens gives the total set bits.
  3. Final Answer:

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

    Clearing bits counts set bits [OK]
Hint: Clear least set bit repeatedly to count set bits [OK]
Common Mistakes:
  • Counting total digits instead of set bits
  • Counting zeros instead of ones
  • Using string length instead of bit operations
2. Which of the following is the correct syntax to clear the least significant set bit in JavaScript using Brian Kernighan's method?
easy
A. n = n | (n - 1);
B. n = n & (n - 1);
C. n = n & (n + 1);
D. n = n ^ (n - 1);

Solution

  1. Step 1: Identify the bit clearing operation

    The correct operation to clear the least significant set bit is n = n & (n - 1).
  2. Step 2: Verify other options

    Other options do not clear the least significant set bit correctly.
  3. Final Answer:

    n = n & (n - 1); -> Option B
  4. Quick Check:

    Use AND with (n-1) to clear bit [OK]
Hint: Use n & (n-1) to clear least set bit [OK]
Common Mistakes:
  • Using OR or XOR instead of AND
  • Adding instead of subtracting 1
  • Confusing bitwise operators
3. What is the output of the following JavaScript code?
function countSetBits(n) {
  let count = 0;
  while (n > 0) {
    n = n & (n - 1);
    count++;
  }
  return count;
}
console.log(countSetBits(13));
medium
A. 3
B. 2
C. 4
D. 5

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 loop clears one set bit, so count increments 3 times before n becomes 0.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    13 (1101) has 3 set bits [OK]
Hint: Count set bits by clearing one bit each loop [OK]
Common Mistakes:
  • Counting total bits instead of set bits
  • Miscounting binary representation
  • Off-by-one errors in loop
4. Identify the error in the following code snippet that uses Brian Kernighan's algorithm:
function countSetBits(n) {
  let count = 0;
  while (n != 0) {
    n = n & (n + 1);
    count++;
  }
  return count;
}
medium
A. Not initializing count to 1
B. Using while loop instead of for loop
C. Missing return statement
D. Using n & (n + 1) instead of n & (n - 1)

Solution

  1. Step 1: Check the bit clearing operation

    The code uses n = n & (n + 1), which does not clear the least significant set bit correctly.
  2. Step 2: Correct operation

    The correct operation is n = n & (n - 1) to clear the least significant set bit.
  3. Final Answer:

    Using n & (n + 1) instead of n & (n - 1) -> Option D
  4. Quick Check:

    Use n & (n-1) to clear bits [OK]
Hint: Use n & (n-1), not n & (n+1) [OK]
Common Mistakes:
  • Using n & (n + 1) which is incorrect
  • Confusing loop types
  • Forgetting to return count
5. Given an array of integers, which code snippet correctly uses Brian Kernighan's algorithm to find the total count of set bits in all elements?
const arr = [3, 5, 7];
// Choose the correct code to count all set bits

A) let total = 0;
for(let n of arr) {
  while(n > 0) {
    n = n & (n - 1);
    total++;
  }
}
console.log(total);

B) let total = 0;
for(let n of arr) {
  total += n.toString(2).length;
}
console.log(total);

C) let total = 0;
for(let n of arr) {
  while(n > 0) {
    n = n | (n - 1);
    total++;
  }
}
console.log(total);

D) let total = 0;
for(let n of arr) {
  total += n & (n - 1);
}
console.log(total);
hard
A. Correctly counts set bits using Brian Kernighan's method
B. Counts total binary digits, not set bits
C. Uses OR instead of AND, incorrect bit clearing
D. Adds bitwise AND result directly, incorrect counting

Solution

  1. Step 1: Identify the correct implementation

    The implementation using while(n > 0) { n = n & (n - 1); total++; } correctly applies Brian Kernighan's algorithm by clearing the least significant set bit repeatedly for each array element and incrementing the total count each time.
  2. Step 2: Eliminate incorrect options

    The option using n.toString(2).length counts all bits including zeros; using n | (n - 1) does not clear set bits correctly; adding n & (n - 1) directly does not count the number of set bits.
  3. Final Answer:

    Correctly counts set bits using Brian Kernighan's method -> Option A
  4. Quick Check:

    Clear bits and count in loop [OK]
Hint: Loop clearing bits per number to sum counts [OK]
Common Mistakes:
  • Counting total binary length instead of set bits
  • Using OR instead of AND for clearing bits
  • Adding bitwise results instead of counts
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