找到小于 X 数的 2 的最大幂?

2022-01-20 00:00:00 python find

问题描述

我正在做这个

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

找到小于 X 数的 2 的最大幂的 Python 方法是什么?

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

编辑例如:power_two(100) 只返回幂

EDIT example: power_two(100) return only the power


解决方案

求对数并截断:

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

相关文章