C++ / easy to understand


  • 0
    M
    vector<int> countBits(int num) {
            // [0000, ..., 1111]
            // [0, ..., 15]
            // int numbers[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
            int bits[]       = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2,  2,  3,  2,  3,  3,  4};
            int fragments = sizeof(int) * 8 / 4;
            vector<int> ret(num + 1, 0);
            for (int i = 1; i <= num; ++i) {
                int count = 0;
                for (int j = 0; j < fragments; ++j) {
                    count += bits[(i >> (4 * j)) % 16];
                }
                ret[i] = count;
            }
            return ret;
        }
    

Log in to reply
 

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