How do I decompose a number into powers of 2?

后端 未结 8 1341
旧巷少年郎
旧巷少年郎 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:43

    The best and fastest way to do this is, of course, with binary numbers, but here's a way with a generator:

    def powers_finder(num):
        d = []
        while sum(d) < num:
            p = powers_of_2()
            a=b=1
            while sum(d)+a<=num:
                b=a
                a = next(p)
            d.append(b)
        d.reverse()
        return d
    
    def powers_of_2():
        n=1
        while 1:
            yield n
            n*=2
    

    >>> print(powers_finder(5))
    [1, 4]
    >>> print(powers_finder(8))
    [8]
    >>> print(powers_finder(9))
    [1, 8]
    >>> print(powers_finder(14))
    [2, 4, 8]
    

提交回复
热议问题