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.
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.
Approach: Following are the steps:
- If n == 1, return “Yes”.
- Else check whether n-1 is a power of 2. Refer this post.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check whether the number has only first and last bits set | Set 2
- Print numbers having first and last bits as the only set bits
- Toggle bits of a number except first and last bits
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Check if bits of a number has count of consecutive set bits in increasing order
- Check if a number has same number of set and unset bits
- Toggle first and last bits of a number
- Check if a number has bits in alternate pattern | Set 1
- Check if a number has two adjacent set bits
- Check if a number has bits in alternate pattern | Set-2 O(1) Approach
- First and Last Three Bits
- Number with set bits only between L-th and R-th index
- Check whether all the bits are set in the given range
- Check whether bits are in alternate pattern in the given range | Set-2
- Check if all bits can be made same by flipping two consecutive bits
- Count pairs in an array such that both elements has equal set bits
- Check whether the two numbers differ at one bit position only
- Check whether all the bits are unset in the given range or not
- Check whether all the bits are unset in the given range
- Check whether bits are in alternate pattern in the given range
Improved By : Sach_Code