- 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

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 −

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))

17

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
- 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 the first and last digit of the smallest number forms a prime in Python
- 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 whether a number has consecutive 0’s in the given base or not using Python
- Check whether the given number is Euclid Number or not in Python
- Prime Number of Set Bits in Binary Representation in Python
- Check whether the specified character has a surrogate code in C#
- Check whether the two numbers differ at one-bit position only in Python

Advertisements