Skip to main content
Back to problems
#191
Easy Algorithms

Number of 1 bits

Divide and Conquer Bit Manipulation
76.4% acceptance
Jan 12, 2026
7149
1370
Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn hamming_weight(n: i32) -> i32 {
    let mut n = n as u32;
    let mut count = 0;
    
    while n != 0 {
      n &= n - 1;
      count += 1;
    }
    
    count
  }
}