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.
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 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
- Check if bits of a number has count of consecutive set bits in increasing order
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Print numbers in the range 1 to n having bits in alternate pattern
- Check if a number has same number of set and unset bits
- 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
- Alternate bits of two numbers to create a new number
- Check if all bits can be made same by flipping two consecutive bits
- Toggle bits of a number except first and last bits
- Count pairs in an array such that both elements has equal set bits
- Print numbers having first and last bits as the only set bits
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Check if all bits of a number are set
- Efficiently check if a string has all unique characters without using any additional data structure
- Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs
- Alternate XOR operations on sorted array