Challenge - 5 Problems
Power of Two Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust code checking power of two?
Consider the following Rust function that checks if a number is a power of two. What will be printed when calling
is_power_of_two(16)?DSA Rust
fn is_power_of_two(n: u32) -> bool { n != 0 && (n & (n - 1)) == 0 } fn main() { println!("{}", is_power_of_two(16)); }
Attempts:
2 left
💡 Hint
Recall that powers of two have only one bit set in binary.
✗ Incorrect
The function returns true if the number is not zero and has exactly one bit set. 16 in binary is 10000, which is a power of two, so output is true.
❓ Predict Output
intermediateWhat does this Rust code print for input 18?
Given the same function
is_power_of_two, what will be printed when calling is_power_of_two(18)?DSA Rust
fn is_power_of_two(n: u32) -> bool { n != 0 && (n & (n - 1)) == 0 } fn main() { println!("{}", is_power_of_two(18)); }
Attempts:
2 left
💡 Hint
Check the binary form of 18 and count set bits.
✗ Incorrect
18 in binary is 10010, which has two bits set, so it is not a power of two. The function returns false.
🔧 Debug
advancedWhat happens when compiling this Rust code?
This Rust function checks if a number is a power of two using a specific expression. What will occur when compiling and running it with input 8?
DSA Rust
fn is_power_of_two(n: u32) -> bool { n != 0 && (n & n - 1) == 0 } fn main() { println!("{}", is_power_of_two(8)); }
Attempts:
2 left
💡 Hint
Rust operator precedence: subtraction (-) has higher precedence than bitwise AND (&).
✗ Incorrect
No compilation error. The expression (n & n - 1) is parsed as n & (n - 1) because subtraction has higher precedence than bitwise AND. For n=8 (1000 in binary), 8 & 7 (0111) == 0, so it returns true.
🧠 Conceptual
advancedWhy does the expression
n & (n - 1) check for power of two?Explain why the bitwise operation
n & (n - 1) equals zero only when n is a power of two.Attempts:
2 left
💡 Hint
Think about binary representation of powers of two and what subtracting 1 does.
✗ Incorrect
A power of two has exactly one bit set. Subtracting 1 flips that bit and sets all lower bits. ANDing with original clears that bit, resulting in zero.
🚀 Application
expertWhat is the output of this Rust code printing powers of two up to 32?
This Rust code prints numbers from 1 to 32 that are powers of two. What is the printed output?
DSA Rust
fn is_power_of_two(n: u32) -> bool { n != 0 && (n & (n - 1)) == 0 } fn main() { for i in 1..=32 { if is_power_of_two(i) { print!("{} ", i); } } }
Attempts:
2 left
💡 Hint
Recall which numbers have exactly one bit set in binary.
✗ Incorrect
The code prints all powers of two between 1 and 32 inclusive: 1, 2, 4, 8, 16, 32.
