Challenge - 5 Problems
Set Bits Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Brian Kernighan's Algorithm for Counting Set Bits
What is the output of this Rust code that counts set bits using Brian Kernighan's algorithm?
DSA Rust
fn count_set_bits(mut n: u32) -> u32 {
let mut count = 0;
while n > 0 {
n &= n - 1;
count += 1;
}
count
}
fn main() {
let number = 29; // binary: 11101
println!("{}", count_set_bits(number));
}Attempts:
2 left
💡 Hint
Count how many 1s are in the binary form of 29 (11101).
✗ Incorrect
Brian Kernighan's algorithm repeatedly removes the rightmost set bit. For 29 (11101), the set bits are at positions 0, 2, 3, and 4, totaling 4.
❓ Predict Output
intermediateResult of Counting Set Bits for Zero
What does the following Rust code print when counting set bits of zero using Brian Kernighan's algorithm?
DSA Rust
fn count_set_bits(mut n: u32) -> u32 {
let mut count = 0;
while n > 0 {
n &= n - 1;
count += 1;
}
count
}
fn main() {
let number = 0;
println!("{}", count_set_bits(number));
}Attempts:
2 left
💡 Hint
Zero has no set bits in binary.
✗ Incorrect
Since zero has no bits set to 1, the count remains zero and the function returns 0.
🔧 Debug
advancedIdentify the Error in Brian Kernighan's Algorithm Implementation
What error will this Rust code produce when trying to count set bits using Brian Kernighan's algorithm?
DSA Rust
fn count_set_bits(mut n: u32) -> u32 {
let mut count = 0;
while n != 0 {
n = n & (n - 1);
count += 1;
}
count
}
fn main() {
let number = 15;
println!("{}", count_set_bits(number));
}Attempts:
2 left
💡 Hint
Check the line where n is updated inside the loop.
✗ Incorrect
The line 'n = n & (n - 1)' is missing a semicolon at the end, causing a syntax error.
❓ Predict Output
advancedOutput of Counting Set Bits for Maximum 8-bit Value
What is the output of this Rust code counting set bits of 255 (all bits set in 8-bit) using Brian Kernighan's algorithm?
DSA Rust
fn count_set_bits(mut n: u8) -> u8 {
let mut count = 0;
while n > 0 {
n &= n - 1;
count += 1;
}
count
}
fn main() {
let number = 255u8; // binary: 11111111
println!("{}", count_set_bits(number));
}Attempts:
2 left
💡 Hint
255 in binary has all 8 bits set to 1.
✗ Incorrect
255 in 8-bit binary is 11111111, which has 8 set bits, so the output is 8.
🧠 Conceptual
expertWhy Brian Kernighan's Algorithm is Efficient for Counting Set Bits
Which statement best explains why Brian Kernighan's algorithm is more efficient than checking each bit individually?
Attempts:
2 left
💡 Hint
Think about how many times the loop runs compared to the total bits.
✗ Incorrect
Brian Kernighan's algorithm loops only as many times as there are set bits, skipping zero bits, making it faster especially for sparse bit patterns.
