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]
比特位计算:
给定一个非负整数n,计算0-n范围内的每个数字i,计算其二进制数中1的数目,并将他们作为数组返回。
1.
class Solution(object):
def count1(self, n):
count=0
while n:
n &= (n-1)
count += 1
return count
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = []
for i in range(num+1):
res.append(self.count1(i))
return res
2.开一个数组,把要算的数字都先存下来count[n+1]={0},
for i =0->n: count[i]=count[i&(i-1)]+1
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res=[0]*(num+1) #列表初始化
for i in range(1,num+1):
res[i]=res[i&(i-1)]+1
return res
初始化列表的方法:
1.初始化递增的list:
list1 = range(10) (不包括10)
#print list1
#[0,1,2,…,9]
2.初始化每项为0的一维数组:
list2 = [0] * 5
#print list2
#[0,0,0,0,0]
3.初始化一个5x6每项为0(固定值)的数组(推荐使用):
multilist = [[0 for col in range(5)] for row in range(6)]