Challenge - 5 Problems
Set Bits Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Brian Kernighan's Algorithm for Counting Set Bits
What is the output of the following JavaScript code that counts the number of set bits (1s) in the binary representation of a number using Brian Kernighan's algorithm?
DSA Javascript
function countSetBits(n) {
let count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
console.log(countSetBits(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. Brian Kernighan's algorithm removes the rightmost set bit in each iteration, so the loop runs 4 times.
❓ Predict Output
intermediateResult of Counting Set Bits for Zero
What will be the output of the following code when counting set bits of 0 using Brian Kernighan's algorithm?
DSA Javascript
function countSetBits(n) {
let count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
console.log(countSetBits(0));Attempts:
2 left
💡 Hint
Zero has no set bits in its binary form.
✗ Incorrect
Since 0 has no bits set to 1, the loop never runs and the count remains 0.
🔧 Debug
advancedIdentify the Error in Brian Kernighan's Algorithm Implementation
What error will the following code produce when trying to count set bits of a positive integer?
DSA Javascript
function countSetBits(n) {
let count = 0;
while (n !== 0) {
n = n & n - 1;
count++;
}
return count;
}
console.log(countSetBits(15));Attempts:
2 left
💡 Hint
Check how the bitwise AND and subtraction operators are grouped.
✗ Incorrect
The expression n & n - 1 is interpreted as (n & n) - 1 due to operator precedence, which is not the intended operation. It causes a logic error.
❓ Predict Output
advancedOutput of Counting Set Bits for a Large Number
What is the output of the following code counting set bits of 1023 using Brian Kernighan's algorithm?
DSA Javascript
function countSetBits(n) {
let count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
console.log(countSetBits(1023));Attempts:
2 left
💡 Hint
1023 is one less than 1024, which is 2^10.
✗ Incorrect
1023 in binary is 1111111111 (ten 1s), so the count of set bits is 10.
🧠 Conceptual
expertWhy Brian Kernighan's Algorithm is Efficient for Counting Set Bits
Why is Brian Kernighan's algorithm more efficient than checking each bit individually when counting set bits in an integer?
Attempts:
2 left
💡 Hint
Think about how many times the loop runs compared to the total bits in the number.
✗ Incorrect
Brian Kernighan's algorithm loops only as many times as there are set bits, skipping zero bits, making it faster especially for numbers with few set bits.
