VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-whether-number-first-last-bits-set/

⇱ Check whether the number has only first and last bits set - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check whether the number has only first and last bits set

Last Updated : 21 Jun, 2022

Given a positive integer n. The problem is to check whether only the first and last bits are set in the binary representation of n.
Examples: 
 

Input : 9
Output : Yes
(9)10 = (1001)2, only the first and
last bits are set.

Input : 15
Output : No
(15)10 = (1111)2, except first and last
there are other bits also which are set.


 

Recommended Practice


Approach: Following are the steps:
 

  1. If n == 1, return "Yes".
  2. Else check whether n-1 is a power of 2. Refer this post.


 

Output: 

Yes

Time Complexity - O(1)

Space Complexity - O(1)
 

Comment
Article Tags:
Article Tags: