Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the count variable to zero.
DSA C
int countSetBits(int n) {
int count = [1];
while (n) {
n = n & (n - 1);
count++;
}
return count;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1 instead of 0.
Using the input variable n as initial count.
✗ Incorrect
The count variable must start at zero to correctly count the number of set bits.
2fill in blank
mediumComplete the code to update n by removing the rightmost set bit.
DSA C
int countSetBits(int n) {
int count = 0;
while (n) {
n = n [1] (n - 1);
count++;
}
return count;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using | (bitwise OR) instead of &.
Using + instead of bitwise operator.
✗ 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 C
int countSetBits(int n) {
int count = 0;
while ([1]) {
n = n & (n - 1);
count++;
}
return count;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using count in the loop condition instead of n.
Using n > 0 which works but less explicit than n != 0.
✗ Incorrect
The loop should continue while n is not 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 C
int countSetBits(int [1]) { int count = 0; while ([2]) { [1] = [1] & ([1] - 1); count++; } return count; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using count as loop variable.
Using incorrect loop condition.
✗ Incorrect
The function parameter and loop variable is n; the loop continues while n is not zero.
5fill in blank
hardFill all three blanks to complete the main function that reads an integer and prints its set bit count.
DSA C
#include <stdio.h> int countSetBits(int n) { int count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } int main() { int [1]; scanf("%d", &[1]); int [2] = countSetBits([3]); printf("%d\n", [2]); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Passing wrong variable to countSetBits.
✗ Incorrect
Variable num stores input; result stores count; num is passed to countSetBits.
