【剑指offer❤️】15.二进制中1个个数

输入一个整数,判断二进制中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;
    }
};

猜你喜欢

转载自blog.csdn.net/beauman/article/details/89600287