首页 > 解决方案 > 在python中将数字表示为两个幂的和的最快方法是什么

问题描述

例如

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

我目前的幼稚实现(取自这里)看起来像这样

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

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

标签: pythonbinarynumbers

解决方案


尝试这个:

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

推荐阅读