### 题目描述

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

``````输入：n = 11 (控制台输入 00000000000000000000000000001011)

``````输入：n = 128 (控制台输入 00000000000000000000000010000000)

``````输入：n = 4294967293 (控制台输入 11111111111111111111111111111101，部分语言中 n = -3）

• 输入必须是长度为 32 的 二进制串

### 题解

O(1)

#### C++ 代码

``````class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
for (int i = 0; i < 32; i ++ )
if (n >> i & 1)
res ++ ;
return res;
}
};``````

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

#### Java 代码

``````public class Solution {
public int hammingWeight(int n) {
int res = 0;
for (int i = 0; i < 32; i ++ ) {
if ((n >> i & 1) == 1) {
res ++ ;
}
}
return res;
}
}``````

``````public class Solution {
public int hammingWeight(int n) {
int res = 0;
while (n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
}``````

#### Python 代码

``````class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
for i in range(32):
if (n >> i) & 1 == 1:
res += 1
return res``````

``````class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
while n != 0:
res += n & 1
n >>= 1
return res``````
{"ft_lang_label":"__label__zh","ft_lang_prob":0.73976207,"math_prob":0.99902034,"size":1799,"snap":"2023-40-2023-50","text_gpt3_token_len":999,"char_repetition_ratio":0.1821727,"word_repetition_ratio":0.25,"special_character_ratio":0.46692607,"punctuation_ratio":0.11904762,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99496055,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-11-29T11:48:19Z\",\"WARC-Record-ID\":\"<urn:uuid:45fed759-58e2-4153-a725-51c1098ce5fe>\",\"Content-Length\":\"54877\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e716cb10-5862-4709-848b-cb2c1438dcbe>\",\"WARC-Concurrent-To\":\"<urn:uuid:b66480f5-4b01-49ab-b778-b88e21e59084>\",\"WARC-IP-Address\":\"69.28.62.189\",\"WARC-Target-URI\":\"https://www.mianshi.online/2694.html\",\"WARC-Payload-Digest\":\"sha1:VYAELNYXWWE3LFU3PRFGHGOXPF2I7VDF\",\"WARC-Block-Digest\":\"sha1:ZMGD5VUDGXGBFCTAVHJQCX3GGBSGEUMI\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-50/CC-MAIN-2023-50_segments_1700679100081.47_warc_CC-MAIN-20231129105306-20231129135306-00876.warc.gz\"}"}