Check whether the number has only first and last bits set in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to check whether the number has only two set bits at first and last position or not.

So, if the input is like n = 17, then the output will be True as the binary representation of n is 10001, there is only two 1's at first and last position.

To solve this, we will follow these steps −

  • if n is same as 1, then
    • return True
  • return true if n - 1 is power of 2, otherwise false

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def is_pow_of_two(n):
   return (n & n-1) == 0

def solve(n):
   if n == 1:
      return True
   return is_pow_of_two (n-1)
      
n = 17
print(solve(n))

Input

17

Output

True
raja
Published on 16-Jan-2021 04:59:42
Advertisements