Concise solution with Python


  • -2
    N
    class Solution(object):
        def countBits(self, num):
            # base case
            if num == 0:
                return [0] 
    
            result = [0]              # keep expanding this list
            currentBlock = 0
            resultLength = num + 1    # expected result length
        
            # keep expanding the result list while it's shorter than expeted
            # by cloning the existing elements and add 1 to each of its element
            while len(result) < resultLength:
                result.extend(map(lambda x: x + 1, result))
                currentBlock = result[-1]
            return result[:resultLength]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.