Given a positive integer n. The problem is to check whether this integer has an alternate pattern in its binary representation or not. Here alternate pattern means that the set and unset bits in n occur in alternate order. For example- 5 has an alternate pattern i.e. 101.
Print “Yes” if it has an alternate pattern otherwise “No”.
Note: 0 < n.
Input : 10 Output : Yes (10)10 = (1010)2, has an alternate pattern. Input : 12 Output : No (12)10 = (1100)2, does not have an alternate pattern.
Simple Approach: It has been discussed in this post having a time complexity of O(n).
Efficient Approach: Following are the steps:
- Calculate num = n ^ (n >> 1). If n has an alternate pattern, then n ^ (n >> 1) operation will produce a number having set bits only. ‘^’ is a bitwise XOR operation.
- Check whether all the bits in num are set or not. 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 email@example.com. 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.
- Check if a number has bits in alternate pattern | Set 1
- Check whether bits are in alternate pattern in the given range | Set-2
- Check whether bits are in alternate pattern in the given range
- Print numbers in the range 1 to n having bits in alternate pattern
- Alternate bits of two numbers to create a new number
- Check if bits of a number has count of consecutive set bits in increasing order
- Check if all bits of a number are set
- Check whether the number has only first and last bits set
- Check whether the number has only first and last bits set | Set 2
- Check if a number has two adjacent set bits
- Check if a number has same number of set and unset 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 or not
- Check whether all the bits are unset in the given range