Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the count variable to zero.
DSA Javascript
function countSetBits(n) {
let count = [1];
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1 instead of 0
Initializing count to n or -1
✗ Incorrect
The count variable should start at 0 because we haven't counted any set bits yet.
2fill in blank
mediumComplete the code to update n by removing the rightmost set bit.
DSA Javascript
function countSetBits(n) {
let count = 0;
while (n > 0) {
n = n [1] (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using bitwise OR (|) instead of AND (&)
Using XOR (^) or addition (+) which do not remove bits
✗ Incorrect
Using bitwise AND (&) between n and (n-1) removes the rightmost set bit.
3fill in blank
hardFix the error in the loop condition to correctly count set bits.
DSA Javascript
function countSetBits(n) {
let count = 0;
while (n [1] 0) {
n = n & (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n < 0 which never runs for positive integers
Using n == 0 which never enters the loop
✗ Incorrect
The loop should continue while n is greater than zero to count all set bits.
4fill in blank
hardFill both blanks to complete the function that counts set bits using Brian Kernighan's algorithm.
DSA Javascript
function countSetBits(n) {
let count = [1];
while (n [2] 0) {
n = n & (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1
Using '<' instead of '>' in the loop condition
✗ Incorrect
Initialize count to 0 and loop while n is greater than 0 to count all set bits.
5fill in blank
hardFill all three blanks to create a function that returns the count of set bits in n using Brian Kernighan's algorithm.
DSA Javascript
function countSetBits(n) {
let count = [1];
while (n [2] 0) {
n = n [3] (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect loop condition operators
Using bitwise OR or XOR instead of AND
✗ Incorrect
Initialize count to 0, loop while n > 0, and update n with n & (n - 1) to remove the rightmost set bit.
