find largest power of two less than X number?

核能气质少年 提交于 2019-12-18 02:27:29

问题


I m doing this

def power_two(n, base = -1):
    result = 2 ** base
    if result < n:
        base += 1
        power_two(n, base)
    else:
        if result == n:
            print base
        else:
            print base - 1

what is the pythonic way to find largest power of two less than X number?

EDIT example: power_two(100) return only the power


回答1:


Find the logarithm and truncate it:

def power_two(n):
    return int(math.log(n, 2))



回答2:


You could use bit_length():

def power_two(n):
    return n.bit_length() - 1

By definition for n != 0: 2**(n.bit_length()-1) <= abs(n) < 2**n.bit_length()




回答3:


Two ways, first works only in Python 2.7 and maybe 3+:

import random
for number in (random.randint(0,1<<32) for _ in range(16)):
    print "%20i,%4i, %4i" % (number, number.bit_length()-1, len(bin(number))-3)



回答4:


utilising the power of .format!

def maxPowOf2(n):
     return len("{0:b}".format(n))-1

This answer is similar and maybe slower than @jfs though...
translates the number into a binary string and finds the length.
Won't work properly on negative numbers though...




回答5:


Um well I'm sure the other suggestions work, but I feel they will perform awfully slow. I haven't actually verified any speeds, but this should be extremely fast!

This is also in Java. So you would need to convert it.

public static int getPowerOfTwo(int size)
{
    int n = -1;
    while (size >> ++n > 0);
    return (1 << n - 1 == size) ? size : 1 << n;
}

public static int getNextPowerOfTwo(int size)
{
    int n = -1;
    while (size >> ++n > 0);
    return 1 << n;
}

public static int getPreviousPowerOfTwo(int size)
{
    int n = -1;
    while (size >> ++n > 0);
    return 1 << n - 1;
}


来源:https://stackoverflow.com/questions/3797575/find-largest-power-of-two-less-than-x-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!