用python将数字表示为2的幂的和的最快方法是什么 [英] What is the fastest way to represent number as the sum of powers of two in python

查看:326
本文介绍了用python将数字表示为2的幂的和的最快方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

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

我目前的幼稚实现(取自此处)

My current naive implementation (taken from here) looks like that

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

但是我希望有更快的方法.

But I hope there're faster ways to do this.

推荐答案

尝试一下:

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

这篇关于用python将数字表示为2的幂的和的最快方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆