leetcode-338. 比特位计数

 

 

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> res;
        int temp = 0;
        for(int i = 0; i <=n;i++){
            temp = countone(i);
            res.push_back(temp);
        }

        return res;
    }

    int countone(int n){
        unsigned int flag = 1;
        int count =0;
        while(flag){
            if(flag&n)
            count++;
            flag = flag<<1;
        }
        return count;
    }
};

 

posted @ 2021-07-24 19:19  三一一一317  阅读(30)  评论(0)    收藏  举报