Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
#include<iostream>
#include<vector>
using namespace std;
typedef unsigned __int32 uint32_t;
int hammingWeight(uint32_t n) {
int count = 0;
while (n)
{
++count;
n = n&(n-1);
}
return count;
}
本文介绍了一个函数,该函数接收一个无符号整数作为输入,并返回其二进制表示中1的个数,即汉明重量。通过示例说明了如何使用此函数来计算特定整数的汉明重量。
4391

被折叠的 条评论
为什么被折叠?



