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;
- Write an Efficient Method to Check if a Number is Multiple of 3
- 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
- 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
- Swap all odd and even bits
- Check if a number is multiple of 9 using bitwise operators
- Check if binary representation of a number is palindrome
- Toggle all the bits of a number except k-th bit.
- Check if a given number is sparse or not
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Mithun Kumar