How to write 4 different functions that check if a number is a power of 2 in Rust

1 Answer

0 votes
// Method A: Bit‑counting using built‑in count_ones()
// A power of two has exactly one bit set.
fn is_power_of_two_a(x: i32) -> bool {
    if x <= 0 {
        return false;
    }
    x.count_ones() == 1
}

// Method B: Classic bitwise trick
// A power of two has only one bit set, so x & (x - 1) == 0.
fn is_power_of_two_b(x: i32) -> bool {
    x > 0 && (x & (x - 1)) == 0
}

// Method C: Repeated division by 2
// Keep dividing until no longer divisible; result must be 1.
fn is_power_of_two_c(mut x: i32) -> bool {
    if x <= 0 {
        return false;
    }
    while x % 2 == 0 {
        x /= 2;
    }
    x == 1
}

// Method D: Using logarithms
// log2(x) must be an integer 
fn is_power_of_two_d(x: i32) -> bool {
    if x <= 0 {
        return false;
    }
    let logv = (x as f64).log2();
    (logv - logv.round()).abs() < 1e-10
}

fn main() {
    let test1 = 16; // true
    let test2 = 18; // false

    println!("A: {}, {}", is_power_of_two_a(test1), is_power_of_two_a(test2));
    println!("B: {}, {}", is_power_of_two_b(test1), is_power_of_two_b(test2));
    println!("C: {}, {}", is_power_of_two_c(test1), is_power_of_two_c(test2));
    println!("D: {}, {}", is_power_of_two_d(test1), is_power_of_two_d(test2));
}



/*
OUTPUT:

A: true, false
B: true, false
C: true, false
D: true, false

*/

 



answered Apr 2 by avibootz

Related questions

...