How to count the number of bits to be flipped to convert a number to another number in Rust

1 Answer

0 votes
fn count_bits(mut num1: u32, mut num2: u32) -> u32 {
    let mut count = 0;
    
    while num1 > 0 || num2 > 0 {
        let lsb1 = num1 & 1;
        let lsb2 = num2 & 1;

        if lsb1 != lsb2 {
            count += 1;
        }

        num1 >>= 1;
        num2 >>= 1;
    }
    
    count
}

fn main() {
    let num1 = 2;  // 00000010
    let num2 = 17; // 00010001
    println!("Number of bits to be flipped: {}", count_bits(num1, num2));

    let num1 = 3;   // 00000011
    let num2 = 221; // 11011101
    println!("Number of bits to be flipped: {}", count_bits(num1, num2));
}



      
/*
run:
  
Number of bits to be flipped: 3
Number of bits to be flipped: 6
 
*/
 

 



answered Oct 27, 2024 by avibootz
...