Find the smallest power of 2 greater than or equal to n in Python

前端 未结 5 2046
说谎
说谎 2020-12-09 15:45

What is the simplest function to return the smallest power of 2 that is greater than or equal to a given non-negative integer in Python?

For example, the smallest po

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 16:07

    Always returning 2**(x - 1).bit_length() is incorrect because although it returns 1 for x=1, it returns a non-monotonic 2 for x=0. A simple fix that is monotonically safe for x=0 is:

    def next_power_of_2(x):  
        return 1 if x == 0 else 2**(x - 1).bit_length()
    

    Sample outputs:

    >>> print(', '.join(f'{x}:{next_power_of_2(x)}' for x in range(10)))
    0:1, 1:1, 2:2, 3:4, 4:4, 5:8, 6:8, 7:8, 8:8, 9:16
    

    It can pedantically be argued that x=0 should return 0 (and not 1), since 2**float('-inf') == 0.

提交回复
热议问题