clueless coding // TODO: be smarter

LeetCode 338. Counting Bits: C++ Solution



Problem Statement


Given a non negative integer number num.

For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Function Signature (C++):
  vector<int> countBits(int num)

Inputs:
  num = 5

Outputs:
  [0,1,1,2,1,2]



TL;DR Code Solution


vector<int> countBits(int num) {

    vector<int> result;

    for (int i = 0; i <= num; i++) {
        int curr = i;
        int current = 0;
        while (curr) {
            curr &= curr - 1;
            current++;
        }
        result.push_back(current);
    }

    return result;

}