338. 比特位计数

class Solution {
public:
    // 除k取余法求二进制 (暴力)
    vector<int> countBits(int n) {
        vector<int> ans;
        for(int i=0;i<=n;i++){
            int t=i;
            int count=0;
            while(t!=0){
                if(t%2==1){
                    count++;
                }
                t/=2;
            }
            ans.push_back(count);
        }
        return ans;
    }
};

posted @ 2022-10-15 13:55  努力、奋斗啊  阅读(20)  评论(0)    收藏  举报