Counting Bits

2019-05-25 22:48:47 浏览数 (1)

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> array;
        for(int i = 0; i <= num; i  ) {
            int current = i;
            int count = 0;
            while(current) {
                current &= (current - 1);
                count  ;
            }
            array.push_back(count);
        }
        return array;
    }
};
  • Version 2
代码语言:javascript复制
class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> array(num   1, 0);
        for(int i = 0; i <= num; i  ) {
            array[i] = array[i >> 1]   (i & 1);
        }
        return array;
    }
};
  • Version 3
代码语言:javascript复制
class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> array(num   1, 0);
        for(int i = 1; i <= num; i  ) {
            array[i] = array[(i & (i - 1))]   1;
        }
        return array;
    }
};
  • Version 4
代码语言:javascript复制
class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> array(num   1, 0);
        for(int i = 1; i <= num; i  ) {
            array[i] = array[i / 2]   (i % 2);
        }
        return array;
    }
};

0 人点赞