Source: https://leetcode.com/problems/counting-bits/

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

/**
* @param {number} n
* @return {number[]}
*/
// nlogn approach:
// For each number up to n
// We count the number of 1s by continuing to integer/floor divide by 2 and checking if odd/even
// if odd we increment the count by 1
// O(nlogn) time, O(1) space
var countBits = function(n) {
const result = new Array(n+1);
for (let i = 0; i <= n; i++) {
let currentNum = i;
let currentOnesCount = 0;
while (currentNum > 0) {
// If it's odd, we increment the number of 1s seen so far
if (currentNum % 2 === 1) {
currentOnesCount += 1;
}
currentNum = Math.floor(currentNum / 2);
}
result[i] = currentOnesCount;
}
return result;
};