输入一个整数,判断二进制中1的个数
java中 :
byte[] cannot be converted to boolean
int cannot be converted to boolean
C++:
class Solution {
public:
int NumberOf1(int n) {
int count=0;;
unsigned int flag = 1;
while(flag){
if(n&flag)
count++;
flag = flag<<1;
}
return count;
}
};
解法二:
class Solution {
public:
int NumberOf1(int n) {
int count=0;
while(n){
n=n&(n-1);
++count;
}
return count;
}
};