I12-leetcode338 three ways to count bits

topic description

Analysis of Algorithms

Method One: Violence

def countBits(self, n: int) -> List[int]:
    #######################################################
    def cnt(x):
        return sum([1 for i in range(32) if x>>i & 1!=0])
    return [cnt(i) for i in range(0,n+1)]

Method 2: Dynamic Programming 1

def countBits(self, n: int) -> List[int]:
    ########################################################
    #方法二:动态规划
    ans=[0]
    for i in range(1,n+1):
        ans.append(ans[i>>1]+(i&1))
    return ans

Method 3: Dynamic Programming 2

def countBits(self, n: int) -> List[int]:
    ########################################################
    #方法三:动态规划
    ans=[0]
    high=0
    for i in range(1,n+1):
        if i&(i-1)==0:
            high=i
        ans.append(ans[i-high]+1)
    return ans

Guess you like

Origin blog.csdn.net/m0_58086930/article/details/128612930