位运算 方法一:
通过 n & 1 来统计当前 nn 的最低位是否为 1,同时每次直接对 n 进行右移并高位补 0。
python
class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
while n:
res += n & 1 # 0&1=0, 1&0=0, 0&0=0, 1&1=1 与 只有遇到1的时候才得1,并计数
n >>= 1 # 右移一位 >>= 意思为:右移后赋值
return res
c++
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while(n){
res += n & 1;
n >>= 1;
}
return res;
}
};
位运算 方法二:
一个朴素的做法是,对 int 的每一位进行检查,并统计 11 的个数。
c++
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
for(int i=0;i<32;i++){
res += ((n>>i) & 1); //
}
return res;
}
};
python
class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
for i in range(32): # n为32位
res += ((n>>i) & 1) # 右移i位后,再 与1
return res
函数:
c++ STL
__builtin_popcount()计算二进制中多少个1
class Solution {
public:
int hammingWeight(uint32_t n) {
return __builtin_popcount(n);
}
};