开发者

find largest power of two less than X number?

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:
  开发者_StackOverflow社区          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


Find the logarithm and truncate it:

def power_two(n):
    return int(math.log(n, 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()


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)


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...


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜