How do I decompose a number into powers of 2?

后端 未结 8 1332
旧巷少年郎
旧巷少年郎 2020-12-20 16:45

I\'m trying to create a function that receives a number as an argument and performs actions on that number to find out its closest powers of 2 that will then add up to that

8条回答
  •  独厮守ぢ
    2020-12-20 17:26

    The idea is to convert the number to binary and then get powers of two from the binary representation:

    #!/usr/bin/env python
    
    
    def get_powers(n):
        """Get positive powers of two which add up to n.
    
        Parameters
        ----------
        n : positive integer
    
        Returns
        -------
        list of integers which are powers of 2
    
        Examples
        --------
        >>> get_powers(14)
        [2, 4, 8]
    
        >>> get_powers(5)
        [1, 4]
        """
        get_bin = lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]
        bin_str = get_bin(n)  # convert n to a binary string
        powers = []
        for i, digit in enumerate(bin_str[::-1]):
            if digit == '1':
                powers.append(2**i)
        return powers
    

提交回复
热议问题