How to count the number of set bits in an integer in Rust

1 Answer

0 votes
fn count_set_bits(mut n: u32) -> u32 {
    let mut count = 0;
    while n > 0 {
        count += n & 1;
        n >>= 1;
    }
    count
}

fn main() {
    let num = 445; // 0001 1011 1101;
    
    println!("The number of set bits in {} is {}", num, count_set_bits(num));
}



   
/*
run:
  
The number of set bits in 445 is 7
  
*/

 



answered Dec 10, 2024 by avibootz

Related questions

1 answer 111 views
1 answer 121 views
2 answers 164 views
2 answers 136 views
...