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;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1 causes off-by-one errors.
Using n as initial count leads to wrong counts.
✗ 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 C++
while (n) { n = n [1] (n - 1); count++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using | instead of & causes incorrect bit manipulation.
Using ^ does not remove the rightmost set bit.
✗ Incorrect
Using bitwise AND with (n - 1) removes the rightmost set bit from n.
3fill in blank
hardFix the error in the loop condition to correctly count set bits.
DSA C++
while ([1]) { n = n & (n - 1); count++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using count in the loop condition causes infinite or no loops.
Using n > 0 or n is better than other variables.
✗ 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 [1](int n) { int count = 0; while (n [2] 0) { n = n & (n - 1); count++; } return count; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '!=' in loop condition may fail for negative numbers.
Using wrong function names causes confusion.
✗ Incorrect
The function name is countSetBits and the loop continues while n is not zero (n != 0).
5fill in blank
hardFill all three blanks to create a main function that reads an integer, counts its set bits, and prints the result.
DSA C++
#include <iostream> int countSetBits(int n) { int count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } int main() { int [1]; std::cin >> [2]; int result = [3](num); std::cout << result << std::endl; return 0; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causes compilation errors.
Calling a wrong function name causes errors.
✗ Incorrect
Variable 'num' is declared and used for input and passed to countSetBits function.
