* 1100&1011 = 1000
* 再让count++即可计算出有多少个1
* @author skyace
*
class Solution {
public:
int NumberOf1(int n) {
int number = 0;
while(n)
{
n &= (n-1);
number++;
}
return number;
}
};
或者用这个:每次将1左移一位,与n&
!!!注意不能用&&,因为&&是逻辑与,只要判断符号两边为true,结果就是1;而&表示的是按位与,结果可以为0x1010即为10
class Solution {
public:
int NumberOf1(int n) {
unsigned int num = (unsigned)n;
int res = 0;
int k = 1;
int m = 32;
while(m)
{
if((num & k) == k)
res++;
k = k << 1;
m--;
}
return res;
}
};