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 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [0,1,1,2,1,2]

Follow up:

  • 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.

根據題目的例子,寫幾個例子出來觀察規律。例如input是2,那i的可能值有0, 1, 2。 0的二進位表示為00,有0個1。 1的二進位表示為01,有1個1。 2的二進位表示為10,有1個1。 所以最終傳回[0, 1, 1]。 可以觀察到規律為dp[i] = dp[i / 2] + (i & 2)。

// Dynamic Programming
vector<int> countBits(int num) { // time: O(n); space: O(n)
    vector<int> dp(num + 1, 0);
    for (int i = 1; i <= num; ++i) {
        dp[i] = dp[i >> 1] + (i & 0x1);
    }
    return dp;
}
191. Number of 1 Bits

Last updated

Was this helpful?