bit manipulation

2016-10-17  本文已影响41人  陈十十
    vector<int> countBits(int num) {
        //ret[i] gives # of 1 in binary representation of i
        vector<int> ret(num+1, 0);
        for (int i=0; i<=num; ++i) {
            int curr = i;
            for (int b=0; b<8*sizeof(int); ++b) {
                ret[i] += curr&1;
                curr>>=1;
            }
        }
        return ret;
    }

side note

    bool isPowOfTwo(int n) {
        return (n & (n - 1)) == 0;
    }

num/2 ===> num>>1
num%2 ===> num&1

    vector<int> countBits(int num) {
        vector<int> ret(num+1, 0);
        for (int i=1; i<num+1; ++i) {
            // ret[i] = ret[i/2] + i%2;
            ret[i] = ret[i>>1] + (i&1); //NOTE: add ()!!! + EXCUTES BEFORE &
            // Or
            ret[i] = ret[i&(i-1)] + 1;  (nearest power of 2)
        }
        return ret;
    }
上一篇下一篇

猜你喜欢

热点阅读