VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-number-has-bits-in-alternate-pattern/

⇱ Check if a number has bits in alternate pattern | Set 1 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a number has bits in alternate pattern | Set 1

Last Updated : 18 Mar, 2025

Given an integer n > 0, the task is to find whether this integer has an alternate pattern in its bits representation. For example- 5 has an alternate pattern i.e. 101. 
Print "Yes" if it has an alternate pattern otherwise "No". Here alternate patterns can be like 0101 or 1010.

Examples: 

Input : 15
Output : No
Explanation: Binary representation of 15 is 1111.

Input : 10
Output : Yes
Explanation: Binary representation of 10 is 1010.

A naive approach to check if a number has bits in alternate patterns:

A simple approach is to find its binary equivalent and then check its bits.  


Output
Yes

Time Complexity: O(log2n)
Auxiliary Space: O(1)

An efficient approach to check if a number has bits in alternate patterns:

1) Right shift the number by 1 (x = n >> 1) so that all 1s become aligned with all 0s for an alternate bit pattern number.
2) Now do an XOR of x with n (y = x ^ n). This will have a number with all 1s. Note that XOR of two bits is 0 when they are same, otherwise 1.
3) Now we mainly need to check if all bits are set or not. To check this, we simply check if y & (y+1) is 0 or not.


Output
Yes

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: