# 191. Number of 1 Bits

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2F53kaXYN14yQdAu8fCUj2%2F%E5%9C%96%E7%89%87.png?alt=media\&token=375ce98a-0876-409a-aace-6e5ce4df7983)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2F7dz84ZPoc9ayupgJJFaF%2F%E5%9C%96%E7%89%87.png?alt=media\&token=15de86fd-a8bb-4fe5-89a2-14dd00838d2e)

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;
    }
}
```
