Given a non-negative number and two values and . The problem is to check whether or not N has an alternate pattern in its binary representation in the range L to R.
Here, alternate pattern means that the set and unset bits occur in alternate order. The bits are numbered from right to left, i.e., the least significant bit is considered to be at first position.
Input : N = 18, L = 1, R = 3 Output : Yes (18)10 = (10010)2 The bits in the range 1 to 3 in the binary representation of 18 are in alternate order. Input : N = 22, L = 2, R = 4 Output : No (22)10 = (10110)2 The bits in the range 2 to 4 in the binary representation of 22 are not in alternate order.
Simple Approach: It has been discussed in this post which has a worst case time complexity of O(log2n).
Efficient Approach: Following are the steps:
- Declare two variables num and left_shift.
- Check if rth bit is set or not in n. Refer this post. If set then, assign num = n and left_shift = r, Else set the (r+1)th bit in n and assign it to num. Refer this post. Also assign left_shift = r + 1.
- Perform num = num & ((1 << left_shift) – 1).
- Perform num = num >> (l – 1).
- Finally check whether bits are in alternate pattern in num or not. Refer this post.
The entire idea of the above approach is to create a number num in which bits are in same pattern as in the given range of n and then check whether bits are in alternate pattern in num or not.
Time Complexity: O(1).
- Check whether bits are in alternate pattern in the given range
- Print numbers in the range 1 to n having bits in alternate pattern
- Check if a number has bits in alternate pattern | Set 1
- Check if a number has bits in alternate pattern | Set-2 O(1) Approach
- 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
- Check if bits in range L to R of two numbers are complement of each other or not
- 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
- Count set bits in a range
- Set all the bits in given range of a number
- Set bits in N equals to M in the given range.
- Copy set bits in a range
- Unset bits in the given range
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.