Bird
0
0
DSA Cprogramming~5 mins

Count Set Bits Brian Kernighan Algorithm in DSA C - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the Brian Kernighan algorithm count in a number?
It counts the number of set bits (1s) in the binary representation of the number.
Click to reveal answer
intermediate
How does the Brian Kernighan algorithm reduce the number of operations compared to checking each bit?
It repeatedly clears the rightmost set bit, reducing the number of iterations to the number of set bits instead of total bits.
Click to reveal answer
intermediate
Explain the operation 'n = n & (n - 1)' in the Brian Kernighan algorithm.
This operation clears the rightmost set bit of n by turning it to 0, effectively reducing the count of set bits by one.
Click to reveal answer
intermediate
What is the time complexity of the Brian Kernighan algorithm for counting set bits?
O(k), where k is the number of set bits in the number, making it efficient for sparse bit patterns.
Click to reveal answer
beginner
Write the basic C code snippet for counting set bits using Brian Kernighan's algorithm.
int countSetBits(int n) { int count = 0; while (n) { n = n & (n - 1); count++; } return count; }
Click to reveal answer
What does the expression 'n & (n - 1)' do in Brian Kernighan's algorithm?
AClears the rightmost set bit of n
BSets the rightmost unset bit of n
CInverts all bits of n
DShifts n to the right by one bit
What is the main advantage of Brian Kernighan's algorithm over checking each bit individually?
AIt counts unset bits instead of set bits
BIt uses less memory
CIt works only for positive numbers
DIt runs in time proportional to the number of set bits, not total bits
If a number has 5 set bits, how many times will the loop run in Brian Kernighan's algorithm?
ANumber of total bits in the number
B5
CDepends on the number's value
DAlways 1
What initial value should the count variable have in the Brian Kernighan algorithm?
ANumber of bits in the integer
B1
C0
DUndefined
Which of these is a correct output of countSetBits(13) using Brian Kernighan's algorithm?
A3
B4
C2
D5
Describe how Brian Kernighan's algorithm counts the set bits in an integer.
Think about how the number changes each loop iteration.
You got /4 concepts.
    Explain why Brian Kernighan's algorithm is more efficient than checking each bit one by one.
    Consider the number of loop iterations.
    You got /4 concepts.