
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 If 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
Advertisements