二进制中1的个数
每位遍历O(n)
class Solution {
public:
int NumberOf1(int n) {
unsigned int flag=1,sum=0;
for(int i=0;i<32;++i){
sum+=flag&n?1:0;
flag<<=1;
}
return sum;
}
};
只遍历1的个数O(m)
class Solution {
public:
int NumberOf1(int n) {
unsigned int sum=0;
while(n!=0){
n=n&(n-1);
sum++;
}
return sum;
}
};