How do I decompose a number into powers of 2?

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

    Most efficient way of doing this:

    def myfunc(x):
        powers = []
        i = 1
        while i <= x:
            if i & x:
                powers.append(i)
            i <<= 1
        return powers
    

提交回复
热议问题