问题描述
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]
.
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.
解题思路
假设返回的序列是dp,通过观察0到num序列可以发现,如果这个数是奇数,则dp[i] = dp[i-1] + 1;如果这个数是偶数则分为①可以被4除尽,②不可以被4除尽两种情况。
可以被4除尽除尽时,dp[i] = dp[i-1] - X + 1;其中X是这个数可以被2除尽的次数
不可以被4除尽时,dp[i] = dp[i-1]
代码如下
class Solution { public: vector<int> countBits(int num) { vector<int> dp; for (int i = 0; i <= num; i++) { dp.push_back(0); } if (num == 0) return dp; for (int i = 1; i <= num; i++) { if (i % 2 != 0) dp[i] = dp[i - 1] + 1; // i 为奇数 else if (i % 4 != 0) dp[i] = dp[i - 1]; // i为不能整除4的偶数 else { // i 为能整除4的偶数 int twos = 0; int tmp = i; while (tmp % 2 == 0) { twos++; tmp /= 2; } dp[i] = dp[i - 1] - twos + 1; } } return dp; } };