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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/bit/191.-number-of-1-bits.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
