Bird
Raised Fist0
DSA C#programming~20 mins

Count Set Bits Brian Kernighan Algorithm in DSA C# - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Brian Kernighan Bit Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Brian Kernighan's Set Bits Count
What is the output of the following C# code that counts set bits using Brian Kernighan's algorithm?
DSA C#
int CountSetBits(int n) {
    int count = 0;
    while (n > 0) {
        n &= (n - 1);
        count++;
    }
    return count;
}

Console.WriteLine(CountSetBits(29));
A4
B3
C2
D5
Attempts:
2 left
💡 Hint
Count how many 1s are in the binary form of 29 (11101).
❓ Predict Output
intermediate
2:00remaining
Result of Counting Set Bits for Zero
What will the output be when counting set bits of 0 using Brian Kernighan's algorithm?
DSA C#
int CountSetBits(int n) {
    int count = 0;
    while (n > 0) {
        n &= (n - 1);
        count++;
    }
    return count;
}

Console.WriteLine(CountSetBits(0));
A-1
B1
CException thrown
D0
Attempts:
2 left
💡 Hint
Zero has no set bits in binary.
🔧 Debug
advanced
2:00remaining
Identify the error in this Brian Kernighan implementation
What error will this code produce when counting set bits?
DSA C#
int CountSetBits(int n) {
    int count = 0;
    while (n != 0) {
        n = n & (n + 1);
        count++;
    }
    return count;
}

Console.WriteLine(CountSetBits(2));
ASyntax error
BReturns correct count 4
CInfinite loop
DReturns 0
Attempts:
2 left
💡 Hint
Check the operation inside the loop carefully.
❓ Predict Output
advanced
2:00remaining
Output of Brian Kernighan's Algorithm on Large Number
What is the output of counting set bits of 1023 using Brian Kernighan's algorithm?
DSA C#
int CountSetBits(int n) {
    int count = 0;
    while (n > 0) {
        n &= (n - 1);
        count++;
    }
    return count;
}

Console.WriteLine(CountSetBits(1023));
A8
B10
C9
D11
Attempts:
2 left
💡 Hint
1023 in binary is all ones in 10 bits.
🧠 Conceptual
expert
2:00remaining
Why does Brian Kernighan's algorithm run in O(k) time?
Brian Kernighan's algorithm to count set bits runs in O(k) time, where k is the number of set bits. Why is this true?
ABecause each iteration removes the rightmost set bit, reducing the number of set bits by one each time
BBecause it loops through all bits from 0 to 31 regardless of set bits
CBecause it uses recursion to count bits
DBecause it counts bits by converting the number to a string
Attempts:
2 left
💡 Hint
Think about what happens to the number in each loop iteration.

Practice

(1/5)
1. What does the Brian Kernighan algorithm do when counting set bits in an integer?
easy
A. It converts the number to a string and counts characters.
B. It counts the total number of digits in the integer.
C. It shifts the bits to the right one by one and counts zeros.
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 on counting set bits

    Each time it clears a set bit, it increments the count 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 counts set bits [OK]
Hint: Clear least set bit repeatedly to count ones [OK]
Common Mistakes:
  • Counting zeros instead of ones
  • Using string conversion to count bits
  • Shifting bits without clearing
2. Which of the following is the correct syntax to clear the least significant set bit in C# using Brian Kernighan's method?
easy
A. n = n & (n - 1);
B. n = n | (n - 1);
C. n = n ^ (n + 1);
D. n = n << 1;

Solution

  1. Step 1: Identify the bit clearing operation

    The expression n = n & (n - 1) clears the least significant set bit in n.
  2. Step 2: Verify other options

    Other options perform different bitwise operations that do not clear the least significant set bit.
  3. Final Answer:

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

    Use n & (n-1) to clear least set bit [OK]
Hint: Use n & (n-1) to clear least set bit [OK]
Common Mistakes:
  • Using OR instead of AND
  • Using XOR with n+1 incorrectly
  • Using left shift which moves bits
3. What is the output of the following C# code snippet?
int countSetBits(int n) {
    int count = 0;
    while (n > 0) {
        n = n & (n - 1);
        count++;
    }
    return count;
}

Console.WriteLine(countSetBits(13));
medium
A. 3
B. 4
C. 2
D. 5

Solution

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

    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 the loop runs 3 times, incrementing count to 3.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Binary 1101 has 3 ones [OK]
Hint: Count 1s in binary of number [OK]
Common Mistakes:
  • Counting total bits instead of set bits
  • Misunderstanding bitwise AND operation
  • Off-by-one errors in loop
4. Identify the error in the following C# 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. Missing return statement
B. Using n & (n + 1) instead of n & (n - 1)
C. Count variable not initialized
D. Incorrect loop condition; should be n > 0

Solution

  1. Step 1: Check the bit clearing expression

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

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

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

    Use n & (n-1) to clear bits [OK]
Hint: Always use n & (n-1) to clear least set bit [OK]
Common Mistakes:
  • Using n & (n + 1) which is incorrect
  • Confusing loop conditions
  • Forgetting to initialize count
5. You want to count set bits in a large list of integers efficiently using Brian Kernighan's algorithm in C#. Which approach is best to optimize performance?
hard
A. Convert each integer to binary string and count '1' characters sequentially.
B. Use a simple for loop shifting bits right and counting set bits sequentially.
C. Use Brian Kernighan's algorithm inside a parallel loop to count bits for each integer concurrently.
D. Store all integers in a list and count set bits only for the first element.

Solution

  1. Step 1: Understand the need for efficiency

    Counting set bits for many integers can be slow if done sequentially.
  2. Step 2: Use parallel processing with Brian Kernighan's algorithm

    Running the efficient bit counting algorithm concurrently on multiple integers speeds up processing.
  3. Final Answer:

    Use Brian Kernighan's algorithm inside a parallel loop to count bits for each integer concurrently. -> Option C
  4. Quick Check:

    Parallel + efficient algorithm = best performance [OK]
Hint: Combine parallelism with Brian Kernighan's method [OK]
Common Mistakes:
  • Using string conversion which is slow
  • Sequential bit shifting which is less efficient
  • Ignoring concurrency for large data
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