1. 题目来源
链接:191. 位1的个数
2. 题目解析
老题了,无非就是枚举每一位,n&(n-1)
,lowbit()
这三种操作来求得二进制串中的 1 的个数。
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while (n) {
n = n & n - 1;
res ++ ;
}
return res;
}
};
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while (n) {
n -= n & -n;
res ++ ;
}
return res;
}
};