Counting bits Kernighan style

To count bits in Rust using the Kernighan method, you can use the following code:

fn count_bits(n: u32) -> u32 {
    let mut count = 0;
    let mut num = n;

    while num != 0 {
        num = num & (num - 1);
        count += 1;
    }

    count
}

This function takes an unsigned 32-bit integer n as input and returns the number of set bits (bits with a value of 1) in n. It uses the Kernighan method, which repeatedly clears the least significant set bit in num until num becomes 0.

To use this function, you can call it with the desired number:

fn main() {
    let number = 42;
    let bit_count = count_bits(number);
    println!("Number of set bits in {}: {}", number, bit_count);
}

This will output:

Number of set bits in 42: 3

Please note that the code provided is a simple implementation of the Kernighan method for counting bits in Rust. There may be other more optimized or efficient ways to count bits in Rust, depending on the specific requirements of your use case.