How do I decompose a number into powers of 2?

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

    The following binary solution combines @moose's use of enumerate() with @gbriones.gdl's use of stride indexing and @gbriones.gdl's comment about one-lining it (actually, it was a comment about not one-lining it, but one-lining is fun).

    def powers(n):
        return [2**p for p,v in enumerate(bin(n)[:1:-1]) if int(v)]
    

提交回复
热议问题