Leetcode:Counting Bits

题目: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]

给定一个非负整数num,给出[0,num]区间内的每个数的二进制表示所含的1的个数,用一个数组输出结果。

解题思路1:利用移位加奇偶数

0:0000 0000 0个

1:0000 0001 1个
2:0000 0010 1个 =1(2>>1或者2/2)中1的个数+2%2
3:0000 0011 2个 =1(3>>1或者3/2)中1的个数+3%2
4:0000 0100 1个 =2(4>>1或者4/2)中1的个数+4%2
5:0000 0101 2个 =2(5>>1或者5/2)中1的个数+5%2
6:0000 0110 2个 =3(6>>1或者6/2)中1的个数+6%2
……
可以使用代码:
list[i]=list[i>>1]+(i%2)
或者
list[i]=list[i>>1]+(i&1)
或者
list[i]=list[i/2]+(i%2)

代码:

class Solution(object):
    def countBits(self,num):
        ans = [0]
        for i in range(1,num+1):
            ans += ans[i>>1]+(i%2)
        return ans

解题思路2:利用相邻数字相与+1

0:0000 0000

1:0000 0001 1个 =0&1 +1
2:0000 0010 1个 =2&1 +1
3:0000 0011 2个 =3&2 +1
……

代码:

class Solution(object):
        def countBits(self,num):
            ans = [0]
            for i in range(1,num+1):
                ans += ans[i%(i-1)]+1
            return ans

你可能感兴趣的:(LeetCode)