/**
* @param {number} n
* @return {number[]}
*/
/**
γ
κ΄κ³μ λ΄ νλ€ κ°μ κ΄κ³ λ° λͺ
μΉμ,
- νΌμ μ (dividend, λλ μ§λ μ) a λ₯Ό,
- μ μ (divisor, λλλ μ : Modulus, λͺ¨λλ¬μ€) m λ‘ λλ λ,
- λͺ« (quotient)μ q,
- λλ¨Έμ§/μμ¬ (remainder, residue)λ₯Ό r μ΄λΌκ³ ν¨
*/
const memo = {};
var countBits = function (n) {
const ans = [];
for (let i = 0; i <= n; i++) {
const cnt = calc2(i);
memo[i] = cnt;
ans.push(cnt);
}
return ans;
};
function calc2(n, cnt = 0) {
if (memo[n] !== undefined) {
return memo[n] + cnt;
}
if (n === 0) {
return cnt;
}
const q = Math.floor(n / 2);
const mod = n % 2;
cnt += mod;
return calc2(q, cnt);
}