0
0
DSA Pythonprogramming~20 mins

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

Choose your learning style9 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 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))
A4
B5
C3
D6
Attempts:
2 left
💡 Hint
Count how many times the loop runs by removing the rightmost set bit each time.
Predict Output
intermediate
2: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))
ANone
B1
C0
DError
Attempts:
2 left
💡 Hint
Zero has no set bits.
🧠 Conceptual
advanced
2: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?
AIt converts the number to a string and counts '1's.
BIt uses recursion to reduce time complexity.
CIt uses a lookup table for all possible bit patterns.
DIt loops only as many times as there are set bits, not total bits.
Attempts:
2 left
💡 Hint
Think about how many times the loop runs compared to total bits.
🔧 Debug
advanced
2: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))
AInfinite loop
BSyntaxError
CReturns 0
DCorrect output 4
Attempts:
2 left
💡 Hint
Check how n changes each iteration with n & (n + 1).
🚀 Application
expert
3: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.
A5
B6
C4
D7
Attempts:
2 left
💡 Hint
List numbers 0 to 15 and count set bits for each.