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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Check if bits of a number has count of consecutive set bits in increasing order
- Check whether the number has only first and last bits set | Set 2
- Check if all bits of a number are set
- Check if a number has two adjacent set bits
- Check if a number has bits in alternate pattern | Set 1
- Check if a number has same number of set and unset bits
- Check if a number has bits in alternate pattern | Set-2 O(1) Approach
- Check if all bits can be made same by flipping two consecutive bits
- Toggle bits of a number except first and last bits
- Check whether all the bits are set in the given range
- Check whether all the bits are unset in the given range
- Check whether all the bits are unset in the given range or not
- Check whether bits are in alternate pattern in the given range | Set-2
- Check whether bits are in alternate pattern in the given range
- Check if bits in range L to R of two numbers are complement of each other or not
Improved By : Sach_Code