标签:
题目:
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:
思路:
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; } };
标签:
原文地址:http://www.cnblogs.com/gavinxing/p/5392637.html