如何将数字分解为 2 的幂? [英] How do I decompose a number into powers of 2?
问题描述
我正在尝试创建一个函数,该函数接收一个数字作为参数并对该数字执行操作以找出其最接近的 2 的幂,然后将其相加到该数字.例如,如果用户输入 4,函数将附加 4,因为它已经是 2 的幂.如果用户输入 14,函数应该看到 14 不是 2 的幂,并且最接近的 2 的幂构成14 是 2,4 和 8.
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 number. For example, if the user enters 4, the function will append 4 because it is already a power of 2. If the user enters a 14 the function should see that 14 is not a power of 2 and the closest powers of 2 that make up 14 are 2,4, and 8.
主要说明:我只会达到 2^9.
Key notes: I am only going up to 2^9.
到目前为止我所拥有的:
What i have so far:
def powers_finder(n):
powers=[]
i=0
total=0
while i<10:
value=2**i
total=total+value
i=i+1
#This if statement is for if the user enters a power of 2 as n
#Then the number will be appended right away into my powers list.
if value==n:
powers.append(value)
这里的问题是,如果用户输入 5 作为 (n) 5 由幂 2^2=4 和 2^0=1 4+1=5 组成.如何扩展我的功能以包含此过程?
The problem here being if the user enters in lets say 5 as (n) 5 is made up of the power 2^2=4 and 2^0=1 4+1=5. How can i extend my function to include this process?
谢谢!
推荐答案
最有效的方法:
def myfunc(x):
powers = []
i = 1
while i <= x:
if i & x:
powers.append(i)
i <<= 1
return powers
这篇关于如何将数字分解为 2 的幂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!