How do I decompose a number into powers of 2?

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

    Rather than solve the problem, how about some information to help you solve it? Take a look at a few examples, and solve them. Here are a few,

    Suppose N=2, then the answer is = {2=2^1}.

    Suppose N=3, then the answer is = {2=2^1,1=2^0} (note that 2**0=1)

    Suppose N=4, then the answer is = {4=2^2}

    ...

    Suppose N=63, then the answer is = {32=2^5, 16=2^4, 8=2^3, 4=2^2, 2=2^1, 1=2^0}

    Suppose N=64, then the answer is = {64=2^6}

    ...

    Suppose N=259, then the answer is = {256=2^8, 2=2^1, 1=2^0}

    Do you see the pattern?


    Want an algorithm?

    Think about these simple steps, and combine them together in a loop,

    Can you check if the number is odd? When the number is odd, then you have detected a bit 'on'. Subtract one (make the number even).

    Can you divide by 2? What do you do with the result?

提交回复
热议问题