Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the count variable to zero.
DSA Typescript
function countSetBits(n: number): number {
let count = [1];
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1 or n instead of 0.
✗ Incorrect
The count variable must start at zero to count the number of set bits correctly.
2fill in blank
mediumComplete the code to update n by removing the rightmost set bit.
DSA Typescript
function countSetBits(n: number): number {
let count = 0;
while (n > 0) {
n = n [1] (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using | or ^ instead of & causes wrong bit manipulation.
✗ Incorrect
Using bitwise AND (&) between n and (n-1) removes the rightmost set bit.
3fill in blank
hardFix the error in the while loop condition to correctly count set bits.
DSA Typescript
function countSetBits(n: number): number {
let count = 0;
while (n [1] 0) {
n = n & (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' or '==' causes infinite or no loops.
✗ Incorrect
The loop should continue while n is greater than zero to count all set bits.
4fill in blank
hardFill both blanks to create a function that counts set bits using Brian Kernighan's algorithm.
DSA Typescript
function countSetBits(n: number): number {
let count = [1];
while (n [2] 0) {
n = n & (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting count at 1 or using wrong 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 using Brian Kernighan's algorithm.
DSA Typescript
function countSetBits(n: number): number {
let count = [1];
while (n [2] 0) {
n = n [3] (n - 1);
count++;
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Wrong initialization, loop condition, or bitwise operator.
✗ Incorrect
Initialize count to 0, loop while n > 0, and update n with n & (n - 1) to remove rightmost set bit.
