338 的题意:
输入一个非负整数num,0 ≤ i ≤ num,输出从0~num 范围内,i转换成二进制所包含的1的个数
要求时间和空间复杂度都是O(n)
以下是我自己写的性能比较差的代码
class Solution(object):
def fun1(self,num):
sum=0
while num:
if num%2==1:
sum+=1
num>>=1
return sum
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
a=[]
for i in range(0,num+1):
a.append(self.fun1(i))
return a
下面为大神解决思路
- 观察发现,1的二进制中数字1的个数是0的加1(),2和3的是0和1的分别加1,4567的是0123的分别加1。找到一种神奇的规律。
0 0 0
1 1 1
2 10 1
3 11 2
4 100 1
5 101 2
6 110 2
7 111 3
8 1000 1
9 1001 2
10 1010 2
11 1011 3
12 1100 2
13 1101 3
14 1110 3
15 1111 4
代码一
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
List1 = [0]
while(len(List1)<=num):
List2 = [i+1 for i in List1]
List1 = List1 + List2
return List1[:num+1]
- 观察发现:偶数的二进制中1的个数和其一半的数的二进制个数相等,奇数的二进制中1的个数是其一半的数的二进制中1的个数加1.比如2和4都是1,3和6都是2。5是2,2是1;7是3,3是2.
另外,整数对应的二进制数逻辑右移一位,就等于除2操作。
代码二
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
List1 = [0]
for i in range(1,num+1):
#>>1为逻辑右移1位,等于除2操作
#偶数对2取余为0,奇数对2取余为1
List1.append(List1[i>>1]+(i%2))
return List1