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.
- 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