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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Write an Efficient Method to Check if a Number is Multiple of 3
- Find the Number Occurring Odd Number of Times
- Check for Integer Overflow
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Compute modulus division by a power-of-2-number
- Find whether a given number is a power of 4 or not
- Add 1 to a given number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Binary representation of a given number
- Swap all odd and even bits
- Check if a number is multiple of 9 using bitwise operators
- How to turn off a particular bit in a number?
- Check if binary representation of a number is palindrome
- Toggle all the bits of a number except k-th bit.
Improved By : Sach_Code