# 191.Number of 1 Bits

**191.Number of 1 Bits**

难度:Easy

> 编写一个函数，输入是一个无符号整数，返回其二进制表达式中数字位数为 ‘1’ 的个数（也被称为汉明重量）。

示例 1：

```
输入：00000000000000000000000000001011
输出：3
解释：输入的二进制串 00000000000000000000000000001011 中，共有三位为 '1'。
示例 2：

输入：00000000000000000000000010000000
输出：1
解释：输入的二进制串 00000000000000000000000010000000 中，共有一位为 '1'。
示例 3：

输入：11111111111111111111111111111101
输出：31
解释：输入的二进制串 11111111111111111111111111111101 中，共有 31 位为 '1'。
```

提示：

请注意，在某些语言（如 Java）中，没有无符号整数类型。在这种情况下，输入和输出都将被指定为有符号整数类型，并且不应影响您的实现，因为无论整数是有符号的还是无符号的，其内部的二进制表示形式都是相同的。 在 Java 中，编译器使用二进制补码记法来表示有符号整数。因此，在上面的 示例 3 中，输入表示有符号整数 -3。

进阶: 如果多次调用这个函数，你将如何优化你的算法？

uint是32位无符号整型，直接每一位相与，计算1的个数。循环32次即可。

```
class Solution {
public:
    int hammingWeight(uint32_t n) {
       uint32_t temp=10000000000000000000000000000000;
        int res=0;
        while(temp)
        {
            if(n & temp) res++;
            temp=temp>>1;
        }
       
      
        return res;
    }
};
```

> 执行用时 : 4 ms, 在Number of 1 Bits的C++提交中击败了98.81% 的用户\
> 内存消耗 : 8.3 MB, 在Number of 1 Bits的C++提交中击败了5.21% 的用户


---

# 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://dfine.gitbook.io/leetcode/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.
