- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

- Related Questions & Answers
- Print numbers having first and last bits as the only set bits
- Check if a number has same number of set and unset bits in C++
- Check if a number has two adjacent set bits in C++
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- First and Last Three Bits in C++
- Check if a number has bits in alternate pattern - Set 1 in C++
- Check if the given decimal number has 0 and 1 digits only in Python
- Check whether a String has only unicode digits in Java
- Check if all bits of a number are set in Python
- Check if a number has bits in alternate pattern - Set-2 O(1) Approach in C++
- Check if the first and last digit of the smallest number forms a prime in Python
- Find the number with set bits only between L-th and R-th index using C++
- Check whether a number has consecutive 0’s in the given base or not using Python
- Python Pandas - Check whether the DateOffset value has been normalized or not
- Python Pandas - Check whether the BusinessDay Offset has been normalized or not

Advertisements