Bird
0
0
DSA Cprogramming~10 mins

Count Set Bits Brian Kernighan Algorithm in DSA C - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A0
B1
C-1
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing count to 1 instead of 0.
Using the input variable n as initial count.
2fill in blank
medium

Complete 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'
A+
B|
C^
D&
Attempts:
3 left
💡 Hint
Common Mistakes
Using | (bitwise OR) instead of &.
Using + instead of bitwise operator.
3fill in blank
hard

Fix 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'
An != 0
Bcount < n
Cn > 0
Dcount != 0
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.
4fill in blank
hard

Fill 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'
An
Bcount
Cn != 0
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Using count as loop variable.
Using incorrect loop condition.
5fill in blank
hard

Fill 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'
Anum
Bresult
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Passing wrong variable to countSetBits.