# LeetCode 338 Counting Bits (递推)

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.

Example:
For num = 5 you should return [0,1,1,2,1,2].

• It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
• Space complexity should be O(n).
• Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

public class Solution {
public int[] countBits(int num) {
int[] dp = new int[num + 1];
Arrays.fill(dp, 0);
dp[0] = 0;
for(int i = 1; i <= num; i ++) {
dp[i] += dp[i >> 1] + (i & 1);
}
return dp;
}
}

#### [leetcode-338]Counting Bits(java)

2016-03-27 20:42:54

#### [leetcode] 338. Counting Bits

2016-03-18 11:57:14

#### LeetCode--338. Counting Bits(计算比特数)Python

2018-01-02 18:35:08

#### leetcode-338-Counting Bits

2016-03-19 11:09:40

#### 338. Counting Bits 数字的二进制中1的个数

2016-05-07 21:31:47

#### leetcode 338 Counting Bits

2017-05-03 20:33:33

#### Counting Bits leetcode 338

2016-04-15 00:24:02

#### LeetCode 338 :Counting Bits

2016-03-30 10:46:17

#### LeetCode[338] Counting Bits

2016-07-25 14:30:24

#### [LeetCode 338] Counting Bits

2016-04-24 13:24:12