题目:
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.
题意:
给定一个非负整数num,写一个函数求出满足0 ≤ i ≤ num的所有数字i的二进制表示中1的个数
代码:
class Solution(object):
def countBits(self, num):"""
:type num: int
:rtype: List[int]
"""
if num < 0 :
return num
else :
result = [0]*(num+1) #定义一个list类型的result,记录从0到num各个数字二进制中1的个数,初始化为0
for i in range(1,num+1) : #遍历1到num,如果i为奇数,则1的个数为i/2的数字对应的二进制中1的个数加1;否则,直接等于i/2的数字对应的二进制中1的个数
if i%2 == 0 :
result[i] = result[i/2]
else :
result[i] = result[i/2] + 1
return result
笔记:
1、初始化一个长度为n的list的方法:lis = [value]*n
2、本题的思路:
任意一个二进制串,左移一位,末尾补0,则相应的十进制为原来的两倍,例如:
111:2^2+2^1+2^0
1110:2^3+2^2+2^1+0 = 2(2^2+2^1+2^0)
相应地,如果任意一个二进制串,左移一位,末尾补1,则相应的十进制为原来的两倍加1
所以,任意一个十进制数n,如果它是偶数,则它对应的二进制串中1的个数与n/2对应的二进制串中1的个数相等
如果它是奇数,则它对应的二进制串中1的个数等于n/2对应的二进制串中1的个数加1
即有递推式:
res(0)=0
res(i)=res(i/2)+(i&1) (i>=1)