VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-number-bits-alternate-pattern-set-2-o1-approach/

⇱ Check if a number has bits in alternate pattern | Set-2 O(1) Approach - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a number has bits in alternate pattern | Set-2 O(1) Approach

Last Updated : 15 Jul, 2022

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

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:
 

  1. 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.
  2. Check whether all the bits in num are set or not. Refer this post.


 

Output : 
 

Yes

Time Complexity : O(1)

Auxiliary Space : O(1) 


 

Comment
Article Tags:
Article Tags: