Complete the code to check if a number is even using bitwise AND.
fn is_even(num: i32) -> bool {
num & [1] == 0
}
fn main() {
let number = 4;
println!("Is even? {}", is_even(number));
}num & 1 equals 1 to find even numbers.The least significant bit of an even number is 0. Using num & 1 checks this bit. If it is 0, the number is even.
Complete the code to print "Odd" if the number is odd using bitwise operation.
fn main() {
let num = 7;
if num & [1] == 1 {
println!("Odd");
} else {
println!("Even");
}
}The last bit of an odd number is 1. Using num & 1 == 1 confirms the number is odd.
Fix the error in the function that returns true if a number is odd using bitwise operation.
fn is_odd(num: i32) -> bool {
num & [1] == 1
}
fn main() {
let number = 5;
println!("Is odd? {}", is_odd(number));
}To check if a number is odd, the last bit must be 1. So num & 1 == 1 returns true for odd numbers.
Fill both blanks to create a function that returns "Even" or "Odd" based on bitwise check.
fn even_or_odd(num: i32) -> &'static str { if num & [1] == [2] { "Even" } else { "Odd" } } fn main() { let number = 10; println!("{}", even_or_odd(number)); }
The function checks if the last bit is 0 for even numbers using num & 1 == 0. Otherwise, it returns "Odd".
Fill all three blanks to create a function that returns true if a number is odd and false if even using bitwise operation.
fn is_odd(num: i32) -> bool {
num [1] [2] == [3]
}
fn main() {
let number = 9;
println!("Is odd? {}", is_odd(number));
}The function uses bitwise AND & with 1 and checks if the result equals 1 to determine if the number is odd.
