题解 | #二进制中1的个数#
二进制中1的个数
https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8
解题思路
- 数字1与数字相位与运算,最后一位为1就是1,最后一位为0就是0。遍历二进制的32位,通过移位0-31次实现。
- 将移位后的1与数字进行位与运算,结果为1就计数器加一。
- 返回计数器。
复杂度
- 时间复杂度为O(1);
- 空间复杂度为O(1)。
代码
python
class Solution:
def NumberOf1(self , n: int) -> int:
res = 0
for i in range(32):
if (n & (1<<i)):
res += 1
return res
C++
class Solution {
public:
int NumberOf1(int n) {
int res = 0;
for(int i = 0; i < 32; i++)
{
if(n&(1<<i))
{
res++;
}
}
return res;
}
};