Complete the code to check if a number is a power of two using bitwise AND.
fn is_power_of_two(n: u32) -> bool {
n != 0 && (n & [1]) == 0
}The expression n & (n - 1) clears the lowest set bit. For powers of two, this results in zero.
Complete the code to return false if the number is zero before checking power of two.
fn is_power_of_two(n: u32) -> bool {
if [1] {
return false;
}
(n & (n - 1)) == 0
}Zero is not a power of two, so we return false immediately if n is zero.
Fix the error in the function signature to accept unsigned 32-bit integers.
fn is_power_of_two(n: [1]) -> bool { n != 0 && (n & (n - 1)) == 0 }
Using u32 ensures the number is unsigned 32-bit, which fits the logic for power of two checks.
Fill both blanks to complete the function that checks if a number is a power of two and print the result.
fn main() {
let num: u32 = 16;
let result = is_power_of_two([1]);
println!("Is power of two: [2]", result);
}
fn is_power_of_two(n: u32) -> bool {
n != 0 && (n & (n - 1)) == 0
}We pass num to the function and use "{}" as the placeholder in println! to print the boolean result.
Fill all three blanks to create a function that checks if a number is a power of two and test it with a different number.
fn main() {
let test_num: u32 = [1];
let check = is_power_of_two([2]);
println!("Number [3] is power of two: {}", test_num, check);
}
fn is_power_of_two(n: u32) -> bool {
n != 0 && (n & (n - 1)) == 0
}We set test_num to 32, pass it to the function, and use {} as the placeholder in println!.
