Finding the Next Power of Two in Python

  • Share this:

Code introduction


This function returns the smallest power of two that is greater than or equal to x. For example, get_next_power_of_two(3) returns 4.


Technology Stack : Built-in libraries: int, bit_length

Code Type : Mathematical calculation function

Code Difficulty : Intermediate


                
                    
def get_next_power_of_two(x):
    return 1 << (x.bit_length() - 1)