Challenge - 5 Problems
Brian Kernighan Bit Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Brian Kernighan's Algorithm for Counting Set Bits
What is the output of the following code that counts set bits using Brian Kernighan's algorithm?
DSA Python
def count_set_bits(n): count = 0 while n: n &= (n - 1) count += 1 return count print(count_set_bits(29))
Attempts:
2 left
💡 Hint
Count how many times the loop runs by removing the rightmost set bit each time.
✗ Incorrect
The number 29 in binary is 11101, which has 4 set bits (1s). Brian Kernighan's algorithm removes one set bit per iteration, so the loop runs 4 times.
❓ Predict Output
intermediate2:00remaining
Result of Counting Set Bits for Zero
What is the output of the code when counting set bits of zero using Brian Kernighan's algorithm?
DSA Python
def count_set_bits(n): count = 0 while n: n &= (n - 1) count += 1 return count print(count_set_bits(0))
Attempts:
2 left
💡 Hint
Zero has no set bits.
✗ Incorrect
Zero in binary is 0, which has no set bits. The loop does not run, so count remains 0.
🧠 Conceptual
advanced2:00remaining
Why Brian Kernighan's Algorithm is Efficient
Why is Brian Kernighan's algorithm more efficient than checking each bit individually to count set bits?
Attempts:
2 left
💡 Hint
Think about how many times the loop runs compared to total bits.
✗ Incorrect
Brian Kernighan's algorithm removes one set bit per iteration, so it runs only as many times as there are set bits, making it faster than checking every bit.
🔧 Debug
advanced2:00remaining
Identify the Error in Modified Brian Kernighan's Code
What error will occur when running this modified code to count set bits?
DSA Python
def count_set_bits(n): count = 0 while n > 0: n = n & (n + 1) count += 1 return count print(count_set_bits(4))
Attempts:
2 left
💡 Hint
Check how n changes each iteration with n & (n + 1).
✗ Incorrect
The expression n & (n + 1) does not remove set bits correctly and can cause n to never become zero, leading to an infinite loop.
🚀 Application
expert3:00remaining
Number of Integers with Exactly k Set Bits in Range
How many integers between 0 and 15 (inclusive) have exactly 2 set bits? Use Brian Kernighan's algorithm to count set bits.
Attempts:
2 left
💡 Hint
List numbers 0 to 15 and count set bits for each.
✗ Incorrect
Numbers with exactly 2 set bits between 0 and 15 are: 3(11), 5(101), 6(110), 9(1001), 10(1010), 12(1100). There are 6 such numbers.