python - 在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')
但我希望有更快的方法来做到这一点。
解决方案
尝试这个:
def two_powers(num):
powers = []
while num != 0:
powers.append(num & -num)
num = num & (num - 1)
return powers
推荐阅读
- c# - 如何在 C# 中跨 2 个图片框画一条线?
- ios - 如何在 iOS 13.3 上使用 xib 显示 UITableViewCell?
- reactjs - 如何使用 React 将变量引用到子组件?
- mongodb - MongoDB查询根据条件将字段从根文档移动到子文档
- coreml - 如何使用 Core ML 分析设备运动值
- swift - 如何检测快速移动的分数节点
- sql - SQL 按列分组,但基于另一列分段
- java - 如何在不跳过 Java 中的零的情况下读取和写入字节
- python - 使用除 spark 之外的 python shell 从 Avro 转换为 Python
- python - Python正则表达式获取包含在{}'中的单词