题目:
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.
思路:
1.检查每一bit是什么,这是它说很简单的思路
2.偶数的话,是前一个数的1的位数 + 1,偶数的话 / 2直到是奇数,因为两杯之间相对于移位,1的位数相同
代码:C++ 思路2:
class Solution { public: vector<int> countBits(int num) { vector<int> solve; if (num < 0) return solve; solve.push_back(0); if (num == 0){ return solve; } for(int i = 1;i <= num;i++){ int index = i; if (i % 2){//i是奇数 solve.push_back(solve.back() + 1); } else{ while (index% 2 == 0) index /= 2; solve.push_back(solve[index]); } } return solve; } };
浙公网安备 33010602011771号