Program to check a number is power of two or not in Python


Suppose we have a number n. We have to check whether this is power of 2 or not.

So, if the input is like n = 2048, then the output will be True as 2048 is 2^11.

To solve this, we will follow these steps −

  • if n is same as 0, then

    • return False

  • return true when (n AND (n - 1)) is same as 0 otherwise false

Example

Let us see the following implementation to get better understanding

def solve(n):
   if n == 0:
      return False
   return (n & (n - 1)) == 0

n = 2048
print(solve(n))

Input

2048

Output

True

Updated on: 11-Oct-2021

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements