How to round a number to the next power of 2 in Python

1 Answer

0 votes
import math

def round_to_next_power_of_2(n: int) -> int:
    """
    Rounds an integer up to the next power of 2.

    Returns:
        int: The next power of 2 greater than or equal to n.
    """
    if n <= 0:
        return 1
        
    return 2 ** math.ceil(math.log2(n))


num = 21
print(f"Next power of 2: {round_to_next_power_of_2(num)}")




'''
run:

Next power of 2: 32

'''

 



answered Oct 29 by avibootz
...