> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/bit/191.-number-of-1-bits.md).

# 191. Number of 1 Bits

![](/files/GKgXcT7GKyxco7VgRxm6)

![](/files/U7G1BpqMNozSFFVqxDtu)

time: O(1)

space: O(1)

```java
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) { // 每次都看最右邊的是否為1
        int count = 0;
        for (int i = 0; i < 32; i++) {
            count += n & 1;
            n = n >> 1;
        }
        return count;
    }
}
```

## optimized

time: O(k), k is the binary length of this num

space: O(1)

```java
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            count++;
            n &= (n-1);
        }
        return count;
    }
}
```
