Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to count set bits using Brian Kernighan's algorithm.
DSA Go
func countSetBits(n int) int {
count := 0
for n > 0 {
n = n [1] (n - 1)
count++
}
return count
}Attempts:
3 left
💡 Hint
Common Mistakes
Using bitwise OR (|) instead of AND (&).
Using XOR (^) which toggles bits incorrectly.
Using shift operators which do not clear bits.
✗ Incorrect
Brian Kernighan's algorithm uses bitwise AND (&) between n and n-1 to clear the least significant set bit.
2fill in blank
mediumComplete the code to initialize the count variable correctly.
DSA Go
func countSetBits(n int) int {
[1] := 0
for n > 0 {
n = n & (n - 1)
count++
}
return count
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name not incremented in the loop.
Using 'sum' or 'result' which are not declared.
✗ Incorrect
The variable 'count' is used to keep track of the number of set bits.
3fill in blank
hardFix the error in the loop condition to correctly process all bits.
DSA Go
func countSetBits(n int) int {
count := 0
for [1] {
n = n & (n - 1)
count++
}
return count
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'n == 0' which stops immediately.
Using 'count < n' which is unrelated to bit count.
✗ Incorrect
The loop continues while n is greater than zero to clear all set bits.
4fill in blank
hardFill both blanks to create a function that counts set bits for multiple numbers.
DSA Go
func countSetBitsInSlice(nums []int) []int {
counts := make([]int, len(nums))
for i, num := range nums {
counts[i] = countSetBits([1])
}
return [2]
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing the whole slice instead of single number.
Returning the input slice instead of counts.
✗ Incorrect
We pass each number 'num' to countSetBits and return the 'counts' slice.
5fill in blank
hardFill all three blanks to implement the main function that tests the countSetBits function.
DSA Go
func main() {
nums := []int{3, 7, 8, 9}
for _, [1] := range nums {
count := countSetBits([2])
fmt.Println("Number:", [3], "Set bits:", count)
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using index variable instead of number.
Printing the slice instead of individual numbers.
✗ Incorrect
The loop variable 'num' is used to get each number and print its set bits count.
