gpt4 book ai didi

python - 在 python 中将数字表示为两个幂之和的最快方法是什么

转载 作者:行者123 更新时间:2023-11-28 19:46:46 25 4
gpt4 key购买 nike

例如

>>> two_powers(42)
>>> (2, 8, 32)

我当前的天真实现(取自 here)看起来像这样

def two_powers(num):
return tuple(2 ** i for i, j in enumerate(bin(num)[-1: 1: -1]) if j == '1')

但我希望有更快的方法来做到这一点。

最佳答案

试试这个:

def two_powers(num):
powers = []
while num != 0:
powers.append(num & -num)
num = num & (num - 1)
return powers

关于python - 在 python 中将数字表示为两个幂之和的最快方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51786324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com