Challenge - 5 Problems
Brian Kernighan Bit Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput 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));
Attempts:
2 left
💡 Hint
Count how many 1s are in the binary form of 29 (11101).
✗ Incorrect
29 in binary is 11101 which has four 1s. Brian Kernighan's algorithm removes the rightmost set bit each iteration, counting how many times it runs.
❓ Predict Output
intermediateResult 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));
Attempts:
2 left
💡 Hint
Zero has no set bits in binary.
✗ Incorrect
Since n is 0, the while loop never runs and count remains 0.
🔧 Debug
advancedIdentify 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));
Attempts:
2 left
💡 Hint
Check the operation inside the loop carefully.
✗ Incorrect
Using n & (n + 1) does not clear the rightmost set bit and can cause an infinite loop.
❓ Predict Output
advancedOutput 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));
Attempts:
2 left
💡 Hint
1023 in binary is all ones in 10 bits.
✗ Incorrect
1023 is 2^10 - 1, so it has 10 set bits.
🧠 Conceptual
expertWhy 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?
Attempts:
2 left
💡 Hint
Think about what happens to the number in each loop iteration.
✗ Incorrect
Each loop iteration clears one set bit, so the number of iterations equals the number of set bits, k.
