📖 Scenario: Imagine you are working with a system that needs to count how many bits are set to 1 in a number's binary form. This is useful in many areas like network masks, permissions, or error detection.
🎯 Goal: You will write a Go program that counts the number of set bits (1s) in an integer using the Brian Kernighan algorithm, which efficiently reduces the number of operations.
📋 What You'll Learn
Create an integer variable named num with the value 29.
Create an integer variable named count initialized to 0.
Use a for loop with the condition num != 0.
Inside the loop, update num using num = num & (num - 1).
Inside the loop, increment count by 1.
Print the value of count.
💡 Why This Matters
🌍 Real World
Counting set bits is useful in network programming, cryptography, and error detection where binary data is common.
💼 Career
Understanding bitwise operations and efficient algorithms is important for system programming, embedded systems, and performance-critical applications.
Progress0 / 4 steps
1
Create the number variable
Create an integer variable called num and set it to 29.
DSA Go
Hint
Use num := 29 to create the variable.
2
Initialize the count variable
Create an integer variable called count and set it to 0 below the num variable.
DSA Go
Hint
Use count := 0 to create the variable.
3
Implement the Brian Kernighan loop
Use a for loop with the condition num != 0. Inside the loop, update num with num = num & (num - 1) and increment count by 1.
DSA Go
Hint
The loop runs while num is not zero. Each iteration removes the rightmost set bit and increases count.
4
Print the count of set bits
Print the value of count using fmt.Println(count). Remember to import the fmt package.
DSA Go
Hint
Use fmt.Println(count) to display the number of set bits.
Practice
(1/5)
1. What does the Brian Kernighan algorithm do when counting set bits in an integer?
easy
A. It repeatedly clears the least significant set bit until the number becomes zero
B. It counts the total number of digits in the binary representation
C. It shifts the number right until it becomes zero and counts the shifts
D. It converts the number to a string and counts '1' characters
Solution
Step 1: Understand the algorithm's main operation
The Brian Kernighan algorithm clears the least significant set bit by doing n = n & (n-1) repeatedly.
Step 2: Effect of clearing bits
Each operation removes one '1' bit, counting how many set bits exist until n becomes zero.
Final Answer:
It repeatedly clears the least significant set bit until the number becomes zero -> Option A
Quick Check:
Clearing bits counts set bits [OK]
Hint: Clear least set bit repeatedly to count ones [OK]
Common Mistakes:
Counting total bits instead of set bits
Using string conversion instead of bitwise operations
Shifting without checking bits
2. Which of the following is the correct syntax for the Brian Kernighan loop in Go to count set bits of an integer n?
easy
A. while n > 0 { count++; n = n - 1 }
B. for n > 0 { count += n & 1; n = n >> 1 }
C. for n != 0 { count++; n = n & (n - 1) }
D. for i := 0; i < 32; i++ { if n & (1 << i) != 0 { count++ } }
Solution
Step 1: Identify the Brian Kernighan loop condition
The loop runs while n is not zero, clearing the least significant set bit each iteration.
Step 2: Confirm the bit clearing operation
The operation n = n & (n - 1) clears the least significant set bit correctly.
Final Answer:
for n != 0 { count++; n = n & (n - 1) } -> Option C
Quick Check:
Loop with n & (n-1) clears bits [OK]
Hint: Use n = n & (n-1) inside for loop [OK]
Common Mistakes:
Using shift instead of bit clear
Using while instead of for in Go
Counting bits by subtracting 1 only
3. What is the output of the following Go code snippet?
func countSetBits(n int) int {
count := 0
for n != 0 {
n = n & (n - 1)
count++
}
return count
}
fmt.Println(countSetBits(13))
medium
A. 2
B. 3
C. 4
D. 5
Solution
Step 1: Convert 13 to binary
13 in binary is 1101, which has three set bits (1s).
Step 2: Apply Brian Kernighan algorithm
Each iteration clears one set bit, so count increments 3 times until n becomes 0.
Final Answer:
3 -> Option B
Quick Check:
Binary 1101 has 3 ones [OK]
Hint: Count ones in binary 13 = 3 [OK]
Common Mistakes:
Counting total bits instead of set bits
Miscounting binary digits
Confusing bitwise AND with OR
4. Identify the error in this Go code snippet that tries to count set bits using Brian Kernighan's algorithm:
func countSetBits(n int) int {
count := 0
for n > 0 {
count = count + (n & 1)
n = n & (n - 1)
}
return count
}
medium
A. Using n & 1 to count bits conflicts with n = n & (n - 1) clearing bits
B. Loop condition should be n != 0 instead of n > 0
C. Count variable should be initialized to 1
D. Missing return statement
Solution
Step 1: Analyze counting method
The code adds n & 1 to count, which checks the least significant bit.
Step 2: Analyze bit clearing step
Then it clears the least significant set bit with n = n & (n - 1), which may skip bits.
Step 3: Conflict explanation
Using both methods together causes incorrect counting because n & 1 and clearing bits are mixed incorrectly.
Final Answer:
Using n & 1 to count bits conflicts with n = n & (n - 1) clearing bits -> Option A
Quick Check:
Mixing bit check and clear causes wrong count [OK]
Hint: Use either bit check or bit clear, not both [OK]
Common Mistakes:
Mixing bitwise AND with bit clearing
Incorrect loop condition
Wrong initialization of count
5. Given a list of integers [7, 8, 15, 23], which Go code snippet correctly uses Brian Kernighan's algorithm to return a map of each integer to its count of set bits?
hard
A. func countSetBits(n int) int {
count := 0
for n != 0 {
n = n & (n - 1)
count++
}
return count
}
func mapSetBits(nums []int) map[int]int {
result := make(map[int]int)
for _, num := range nums {
result[countSetBits(num)] = num
}
return result
}
B. func countSetBits(n int) int {
count := 0
for n > 0 {
count += n & 1
n = n >> 1
}
return count
}
func mapSetBits(nums []int) map[int]int {
result := make(map[int]int)
for i := 0; i < len(nums); i++ {
result[i] = countSetBits(nums[i])
}
return result
}
C. func countSetBits(n int) int {
count := 0
for n != 0 {
n = n & (n - 1)
count++
}
return count
}
func mapSetBits(nums []int) map[int]int {
result := make(map[int]int)
for i, num := range nums {
result[i] = countSetBits(num)
}
return result
}
D. func countSetBits(n int) int {
count := 0
for n != 0 {
n = n & (n - 1)
count++
}
return count
}
func mapSetBits(nums []int) map[int]int {
result := make(map[int]int)
for _, num := range nums {
result[num] = countSetBits(num)
}
return result
}
Solution
Step 1: Check countSetBits function correctness
func countSetBits(n int) int {
count := 0
for n != 0 {
n = n & (n - 1)
count++
}
return count
}
func mapSetBits(nums []int) map[int]int {
result := make(map[int]int)
for _, num := range nums {
result[num] = countSetBits(num)
}
return result
} uses Brian Kernighan's algorithm correctly to count set bits.
Step 2: Check mapSetBits function logic
The mapSetBits function correctly maps each number (as key) to its set bit count (as value).
Step 3: Verify other options
func countSetBits(n int) int {
count := 0
for n > 0 {
count += n & 1
n = n >> 1
}
return count
}
func mapSetBits(nums []int) map[int]int {
result := make(map[int]int)
for i := 0; i < len(nums); i++ {
result[i] = countSetBits(nums[i])
}
return result
} uses shift method and wrong map keys; func countSetBits(n int) int {
count := 0
for n != 0 {
n = n & (n - 1)
count++
}
return count
}
func mapSetBits(nums []int) map[int]int {
result := make(map[int]int)
for i, num := range nums {
result[i] = countSetBits(num)
}
return result
} uses index as key; func countSetBits(n int) int {
count := 0
for n != 0 {
n = n & (n - 1)
count++
}
return count
}
func mapSetBits(nums []int) map[int]int {
result := make(map[int]int)
for _, num := range nums {
result[countSetBits(num)] = num
}
return result
} reverses key and value.
Final Answer:
The code that maps num to countSetBits(num) -> Option D
Quick Check:
Map keys are numbers, values are counts [OK]
Hint: Map number to countSetBits result using correct keys [OK]
Common Mistakes:
Using index as map key instead of number
Swapping keys and values in map
Using shift method instead of Brian Kernighan
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.