Binary Counting with bit manipulation


  • 0
    I
    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int>res;
            for(int i=0;i<=num;++i){
                res.push_back(bits(i));
            }
            return res;
        }
        int bits(int n){
            n=(n&0x55555555)+(n>>1&0x55555555);
            n=(n&0x33333333)+(n>>2&0x33333333);
            n=(n&0x0f0f0f0f)+(n>>4&0x0f0f0f0f);
            n=(n&0x00ff00ff)+(n>>8&0x00ff00ff);
            n=(n&0x0000ffff)+(n>>16&0x0000ffff);
            return n;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.