题目
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
3Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011
Example 2:1
2
3Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000
分析
这是一个明显的位运算的问题,尤其是实例中的解释的问题,尤其显示为对位进行的操作,因此这里有一个简单的方法,时间复杂度比较的低,对最后一位进行按位与运算。
C语言代码
1 | int hammingWeight(uint32_t n) { |