LeetCode-191. Number of 1 Bits

题目

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Example 1:

1
2
3
Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011

Example 2:

1
2
3
Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000

分析

这是一个明显的位运算的问题,尤其是实例中的解释的问题,尤其显示为对位进行的操作,因此这里有一个简单的方法,时间复杂度比较的低,对最后一位进行按位与运算。

C语言代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int hammingWeight(uint32_t n) {
int normal=0;
while(n)
{
// 对n和1求位运算 指定最后一位为1的位运算
if(n & 1)
{
++normal;
}
// 对n进行向右移动
n>>=1;
}
return normal;

}