# x 338. Counting Bits

{% embed url="<https://leetcode.com/problems/counting-bits/solutions/79539/three-line-java-solution/>" %}

#### 2nd try - optimized

```java
/**
 * @param {number} n
 * @return {number[]}
 */
var countBits = function(n) {
    const ans = new Array(n + 1);
    ans[0] = 0;
    for (let i = 1; i <= n; i++) {
        ans[i] = ans[i >> 1] + (i & 1);
    }

    return ans;
};
```

#### 1st try

> time: O(N)

> space: O(N)

```jsx
/**
 * @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);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/binary/x-338.-counting-bits.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
