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.
Approach
- 题目大意为给你一个区间num,返回0~num中每个数的二进制数中1的数量为多少,这道题很有趣,有两个比较常见解法,一个是借用库bitset可以直接算出1的数量为多少,还有一个解法就是用递推解,dp[0]=0,dp[1]=dp[0]+1,dp[2]=dp[0]+1,dp[3]=dp[1]+1,dp[4]=dp[0]+1,dp[5]=dp[1]+1,dp[6]=dp[2]+1,dp[7]=dp[3]+1,dp[8]=dp[0]+1….
Code
One
class Solution {
public:
vector<int> countBits(int num) {
vector<int>nums;
nums.push_back(0);
while (nums.size() <= num) {
int lim = nums.size();
for (int i = 0; i < lim&&i + lim <= num; i++) {
nums.push_back(nums[i] + 1);
}
}
return nums;
}
};
Two
class Solution {
public:
vector<int> countBits(int num) {
vector<int>nums;
for (int i = 0; i <= num; i++) {
nums.push_back(bitset<32>(i).count());
}
return nums;
}
};