leetcode 191. 位1的个数
给定一个正整数 n
,编写一个函数,获取一个正整数的二进制形式并返回其二进制表达式中设置位的个数。1 <= n <= 2^32-1
法一:暴力解:
class Solution { public: int hammingWeight(uint32_t n) { int count=0; while(n){ if(n%2==1) count++; n /= 2; } return count; } };
法二:逐位判断
对于二进制数字n
若 n & 1 = 1 ,那么 n 二进制最右位为 1
若 n & 1 = 0 ,那么 n 二进制最右位为 0
class Solution {
public:
int hammingWeight(int n) {
int res = 0; // c++ 使用无符号数
while (n != 0) {
res += (n & 1);//若 n & 1 = 1 ,那么 n 二进制最右位为 1; 若 n & 1 = 0 ,那么 n 二进制最右位为 0
n = n >> 1;//n的二进制右移一位
}
return res;
}
};
法三:利用 n & (n-1)
class Solution {
public:
int hammingWeight(int n) {
int res = 0;
while (n != 0) {
n &= n - 1;
res++;
}
return res;
}
};