Given a non-negative number n and two values l and r. 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.
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
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.
bitsAreInAltPatrnInGivenTRange(n, l, r) // Shift bits of given number n by // (l-1). num = n >> (l - 1) // Find first bit of range prev = num & 1 // Traverse through remaining // bits. For every bit, check if // current bit is same as previous // or not. num = num >> 1 for i = 1 to (r - l) curr = num & 1 if curr == prev then return false prev = curr num = num >> 1 return true;
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Check whether bits are in alternate pattern in the given range | Set-2
- 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
- Check if all bits can be made same by flipping two consecutive bits
- Set all the bits in given range of a number
- Copy set bits in a range
- Toggle bits in the given 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.
Improved By : Mithun Kumar