1、题目:
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]
.
2、解答: 就是一个十进制数转换为二进制的过程。除2取余 f[i] = f[i/2] + i%2;
3、代码
C++代码
class Solution {
public:
vector<int> countBits(int num) {
vector<int> f(num+1,0);
for(int i=1;i<=num;i++)
f[i] = f[i>>1] + (i&1);
return f;
}
};
python代码
class Solution:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
f = [0]*(num+1)
for i in range(1,num+1):
f[i] = f[i>>1] + (i&1)
return f