[][src]Function leetcode_for_rust::cd0191_number_of_bits::hamming_weight

pub fn hamming_weight(n: u32) -> i32

Solutions

Approach 1: Loop and Flip

  • Time complexity: O(1)

  • Space complexity: O(1)

  • Runtime:

  • Memory:

impl Solution {
    pub fn hamming_weight(mut n: u32) -> i32 {
        let mut count = 0;
        let mut mask = 1;
        for i in 0..32 {
            if n & mask != 0 { count += 1; }
            mask <<= 1
        }
        count
    }
}

Approach 2: Loop and Flip

  • Time complexity: O(1)

  • Space complexity: O(1)

  • Runtime:

  • Memory:

impl Solution {
    pub fn hamming_weight(mut n: u32) -> i32 {
        let mut count = 0;
        for i in 0..32 {
            if n & 1 == 1 { count += 1; }
            n >>= 1
        }
        count
    }
}

Approach 3: Bit Manipulation Trick

  • Time complexity: O(1)

  • Space complexity: O(1)

  • Runtime:

  • Memory:

impl Solution {
    pub fn hamming_weight(mut n: u32) -> i32 {
        let mut count = 0;
        while n != 0 {
            count += 1;
            n &= (n - 1);
        }
        count
    }
}