小编sta*_*ker的帖子

如何将数字分解为2的幂?

我正在尝试创建一个函数,该函数接收一个数字作为参数,并对该数字执行操作以找出其最接近2的幂,然后将该数字加起来.例如,如果用户输入4,则该函数将附加4,因为它已经是2的幂.如果用户输入14,则该函数应该看到14不是2的幂,并且最接近2的幂组成14是2,4和8.

主要提示:我只能达到2 ^ 9.

到目前为止我有什么:

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)
Run Code Online (Sandbox Code Playgroud)

这里的问题是,如果用户输入,则假设5为(n)5由功率2 ^ 2 = 4和2 ^ 0 = 1 4 + 1 = 5组成.如何扩展我的功能以包含此过程?

谢谢!

python python-3.x

7
推荐指数
2
解决办法
6725
查看次数

标签 统计

python ×1

python-3.x ×1