---
# System prepended metadata

title: \#338 Counting Bits
tags: [leetcode, leetcode-easy, DP]

---

# \#338 Counting Bits
## *給定十進位整數n, 列出0~n-1的二進位制中, 每個數字裡"1"的出現次數(以陣列型態回傳)*
## Log
 - build 20210617 by syhuang

## trick
 - result[i] = result[i/2] + i%2
```javascript=
var countBits = function(n) {
    let result = [0];
    for(let i=1; i<=n; i++) result.push(result[Math.floor(i/2)]+i%2);
    return result;
};
```
## 備註
 - DP
## 參考
 - [參考解](https://leetcode.com/problems/counting-bits/discuss/79539/Three-Line-Java-Solution)
###### tags: `leetcode`, `leetcode-easy`, `DP`