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.
Examples:
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.
C++
// C++ implementation to check whether bits are in // alternate pattern in the given range #include <bits/stdc++.h> using namespace std; // function to check whether rightmost // kth bit is set or not in 'n' bool isKthBitSet(unsigned int n, unsigned int k) { if ((n >> (k - 1)) & 1) return true ; return false ; } // function to set the rightmost kth bit in 'n' unsigned int setKthBit(unsigned int n, unsigned int k) { // kth bit of n is being set by this operation return ((1 << (k - 1)) | n); } // function to check if all the bits are set or not // in the binary representation of 'n' bool allBitsAreSet(unsigned int n) { // if true, then all bits are set if (((n + 1) & n) == 0) return true ; // else all bits are not set return false ; } // function to check if a number // has bits in alternate pattern bool bitsAreInAltOrder(unsigned int n) { unsigned int num = n ^ (n >> 1); // to check if all bits are set // in 'num' return allBitsAreSet(num); } // function to check whether bits are in // alternate pattern in the given range bool bitsAreInAltPatrnInGivenRange(unsigned int n, unsigned int l, unsigned int r) { unsigned int num, left_shift; // preparing a number 'num' and 'left_shift' // which can be further used for the check // of alternate pattern in the given range if (isKthBitSet(n, r)) { num = n; left_shift = r; } else { num = setKthBit(n, (r + 1)); left_shift = r + 1; } // unset all the bits which are left to the // rth bit of (r+1)th bit num = num & ((1 << left_shift) - 1); // right shift 'num' by (l-1) bits num = num >> (l - 1); return bitsAreInAltOrder(num); } // Driver program to test above int main() { unsigned int n = 18; unsigned int l = 1, r = 3; if (bitsAreInAltPatrnInGivenRange(n, l, r)) cout << "Yes" ; else cout << "No" ; return 0; } |
Java
// Java implementation to check whether bits are in // alternate pattern in the given range class GFG { // function to check whether rightmost // kth bit is set or not in 'n' static boolean isKthBitSet( int n, int k) { if ((n >> (k - 1 )) == 1 ) return true ; return false ; } // function to set the rightmost kth bit in 'n' static int setKthBit( int n, int k) { // kth bit of n is being set by this operation return (( 1 << (k - 1 )) | n); } // function to check if all the bits are set or not // in the binary representation of 'n' static boolean allBitsAreSet( int n) { // if true, then all bits are set if (((n + 1 ) & n) == 0 ) return true ; // else all bits are not set return false ; } // function to check if a number // has bits in alternate pattern static boolean bitsAreInAltOrder( int n) { int num = n ^ (n >> 1 ); // to check if all bits are set // in 'num' return allBitsAreSet(num); } // function to check whether bits are in // alternate pattern in the given range static boolean bitsAreInAltPatrnInGivenRange( int n, int l, int r) { int num, left_shift; // preparing a number 'num' and 'left_shift' // which can be further used for the check // of alternate pattern in the given range if (isKthBitSet(n, r)) { num = n; left_shift = r; } else { num = setKthBit(n, (r + 1 )); left_shift = r + 1 ; } // unset all the bits which are left to the // rth bit of (r+1)th bit num = num & (( 1 << left_shift) - 1 ); // right shift 'num' by (l-1) bits num = num >> (l - 1 ); return bitsAreInAltOrder(num); } // Driver code public static void main(String[] args) { int n = 18 ; int l = 1 , r = 3 ; if (bitsAreInAltPatrnInGivenRange(n, l, r)) System.out.println( "Yes" ); else System.out.println( "No" ); } } // This code has been contributed by 29AjayKumar |
Python3
# Python 3 implementation to check # whether bits are in alternate pattern # in the given range # function to check whether rightmost # kth bit is set or not in 'n' def isKthBitSet(n, k): if ((n >> (k - 1 )) & 1 ): return True return False # function to set the rightmost kth bit in 'n' def setKthBit(n, k): # kth bit of n is being set # by this operation return (( 1 << (k - 1 )) | n) # function to check if all the bits are set or not # in the binary representation of 'n' def allBitsAreSet(n): # if true, then all bits are set if (((n + 1 ) & n) = = 0 ): return True # else all bits are not set return False # function to check if a number # has bits in alternate pattern def bitsAreInAltOrder(n): num = n ^ (n >> 1 ) # to check if all bits are set # in 'num' return allBitsAreSet(num) # function to check whether bits are in # alternate pattern in the given range def bitsAreInAltPatrnInGivenRange(n, l, r): # preparing a number 'num' and 'left_shift' # which can be further used for the check # of alternate pattern in the given range if (isKthBitSet(n, r)): num = n left_shift = r else : num = setKthBit(n, (r + 1 )) left_shift = r + 1 # unset all the bits which are left to the # rth bit of (r+1)th bit num = num & (( 1 << left_shift) - 1 ) # right shift 'num' by (l-1) bits num = num >> (l - 1 ) return bitsAreInAltOrder(num) # Driver Code if __name__ = = '__main__' : n = 18 l = 1 r = 3 if (bitsAreInAltPatrnInGivenRange(n, l, r)): print ( "Yes" ) else : print ( "No" ) # This code is contributed by # Surendra_Gangwar |
C#
// C# implementation to check whether bits are in // alternate pattern in the given range using System; class GFG { // function to check whether rightmost // kth bit is set or not in 'n' static bool isKthBitSet( int n, int k) { if ((n >> (k - 1)) == 1) return true ; return false ; } // function to set the rightmost kth bit in 'n' static int setKthBit( int n, int k) { // kth bit of n is being set by this operation return ((1 << (k - 1)) | n); } // function to check if all the bits are set or not // in the binary representation of 'n' static bool allBitsAreSet( int n) { // if true, then all bits are set if (((n + 1) & n) == 0) return true ; // else all bits are not set return false ; } // function to check if a number // has bits in alternate pattern static bool bitsAreInAltOrder( int n) { int num = n ^ (n >> 1); // to check if all bits are set // in 'num' return allBitsAreSet(num); } // function to check whether bits are in // alternate pattern in the given range static bool bitsAreInAltPatrnInGivenRange( int n, int l, int r) { int num, left_shift; // preparing a number 'num' and 'left_shift' // which can be further used for the check // of alternate pattern in the given range if (isKthBitSet(n, r)) { num = n; left_shift = r; } else { num = setKthBit(n, (r + 1)); left_shift = r + 1; } // unset all the bits which are left to the // rth bit of (r+1)th bit num = num & ((1 << left_shift) - 1); // right shift 'num' by (l-1) bits num = num >> (l - 1); return bitsAreInAltOrder(num); } // Driver code public static void Main() { int n = 18; int l = 1, r = 3; if (bitsAreInAltPatrnInGivenRange(n, l, r)) Console.WriteLine( "Yes" ); else Console.WriteLine( "No" ); } } /* This code contributed by PrinciRaj1992 */ |
Javascript
<script> // Javascript implementation to check whether bits are in // alternate pattern in the given range // function to check whether rightmost // kth bit is set or not in 'n' function isKthBitSet(n, k) { if ((n >> (k - 1)) & 1) return true ; return false ; } // function to set the rightmost kth bit in 'n' function setKthBit(n, k) { // kth bit of n is being set by this operation return ((1 << (k - 1)) | n); } // function to check if all the bits are set or not // in the binary representation of 'n' function allBitsAreSet(n) { // if true, then all bits are set if (((n + 1) & n) == 0) return true ; // else all bits are not set return false ; } // function to check if a number // has bits in alternate pattern function bitsAreInAltOrder(n) { var num = n ^ (n >> 1); // to check if all bits are set // in 'num' return allBitsAreSet(num); } // function to check whether bits are in // alternate pattern in the given range function bitsAreInAltPatrnInGivenRange(n, l, r) { var num, left_shift; // preparing a number 'num' and 'left_shift' // which can be further used for the check // of alternate pattern in the given range if (isKthBitSet(n, r)) { num = n; left_shift = r; } else { num = setKthBit(n, (r + 1)); left_shift = r + 1; } // unset all the bits which are left to the // rth bit of (r+1)th bit num = num & ((1 << left_shift) - 1); // right shift 'num' by (l-1) bits num = num >> (l - 1); return bitsAreInAltOrder(num); } // Driver program to test above var n = 18; var l = 1, r = 3; if (bitsAreInAltPatrnInGivenRange(n, l, r)) document.write( "Yes" ); else document.write( "No" ); </script> |
Yes
Time Complexity: O(1)
Auxiliary space: O(1)
Example in c:
Approach:
Check if the given range has odd or even number of bits.
a. If it has odd number of bits, all numbers in the range will start with a 0 or 1 bit.
b. If it has even number of bits, all numbers in the range will alternate between 01 and 10 bit patterns.
Traverse the range and check if all numbers in the range follow the appropriate pattern:
a. If the range has odd number of bits, check if the first bit of the number is the same as the first bit of the starting number.
b. If the range has even number of bits, check if the number is alternating between 01 and 10 bit patterns by checking if the parity (even or odd) of the number is the same as the parity of the starting number.
If all numbers in the range follow the appropriate pattern, return true. Otherwise, return false.
C++
#include <iostream> // Function to check if alternate bits are set in the given // range bool checkAlternateBits( int num, int left, int right) { // Create a mask to extract the bits in the specified // range int mask = ((1 << (right - left + 1)) - 1) << (left - 1); // Extract the bits in the specified range and shift // them to the rightmost positions int maskedNum = (num & mask) >> (left - 1); // Extract even and odd bits using bit masks int evenBits = maskedNum & 0xAAAAAAAA; // Bits at even positions int oddBits = maskedNum & 0x55555555; // Bits at odd positions // Check if either even or odd bits are set while the // other is not return (evenBits && !oddBits) || (!evenBits && oddBits); } int main() { int num, left, right; std::cout << "Enter the number: " ; std::cin >> num; std::cout << "Enter the left and right range: " ; std::cin >> left >> right; if (checkAlternateBits(num, left, right)) { std::cout << "Yes" << std::endl; } else { std::cout << "No" << std::endl; } return 0; } |
C
#include <stdio.h> int check_alternate_bits( int num, int left, int right) { int mask = ((1 << (right - left + 1)) - 1) << (left - 1); int masked_num = (num & mask) >> (left - 1); int even_bits = masked_num & 0xAAAAAAAA; // bits at even positions int odd_bits = masked_num & 0x55555555; // bits at odd positions return (even_bits && !odd_bits) || (!even_bits && odd_bits); } int main() { int num, left, right; printf ( "Enter the number: " ); scanf ( "%d" , &num); printf ( "Enter the left and right range: " ); scanf ( "%d%d" , &left, &right); if (check_alternate_bits(num, left, right)) { printf ( "Yes\n" ); } else { printf ( "No\n" ); } return 0; } |
Java
import java.util.Scanner; public class Main { // Function to check if alternate bits are set in the // given range static boolean checkAlternateBits( int num, int left, int right) { // Create a mask to extract the bits in the // specified range int mask = (( 1 << (right - left + 1 )) - 1 ) << (left - 1 ); // Extract the bits in the specified range and shift // them to the rightmost positions int maskedNum = (num & mask) >> (left - 1 ); // Extract even and odd bits using bit masks int evenBits = maskedNum & 0xAAAAAAAA ; // Bits at even positions int oddBits = maskedNum & 0x55555555 ; // Bits at odd positions // Check if either even or odd bits are set while // the other is not return (evenBits != 0 && oddBits == 0 ) || (evenBits == 0 && oddBits != 0 ); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { System.out.print( "Enter the number: " ); int num = scanner.nextInt(); System.out.print( "Enter the left and right range: " ); int left = scanner.nextInt(); int right = scanner.nextInt(); if (left > right || left < 1 ) { System.out.println( "No" ); } else { if (checkAlternateBits(num, left, right)) { System.out.println( "Yes" ); } else { System.out.println( "No" ); } } } catch (Exception e) { System.out.println( "No" ); } finally { scanner.close(); } } } |
Python3
# code def check_alternate_bits(num, left, right): # Create a mask to extract the bits in the specified range mask = (( 1 << (right - left + 1 )) - 1 ) << (left - 1 ) # Extract the bits in the specified range and shift them to the rightmost positions masked_num = (num & mask) >> (left - 1 ) # Extract even and odd bits using bit masks even_bits = masked_num & 0xAAAAAAAA # Bits at even positions odd_bits = masked_num & 0x55555555 # Bits at odd positions # Check if either even or odd bits are set while the other is not return (even_bits and not odd_bits) or ( not even_bits and odd_bits) if __name__ = = "__main__" : num = 18 left, right = 1 , 3 if check_alternate_bits(num, left, right): print ( "Yes" ) else : print ( "No" ) # This code is Contributed by Suchethan |
C#
using System; class Program { // Function to check if alternate bits are set in the given range static bool CheckAlternateBits( int num, int left, int right) { // Create a mask to extract the bits in the specified range long mask = ((1L << (right - left + 1)) - 1) << (left - 1); // Extract the bits in the specified range and shift them to the rightmost positions int maskedNum = ( int )((num & mask) >> (left - 1)); // Extract even and odd bits using bit masks int evenBits = maskedNum & 0xAAAAAAAA; // Bits at even positions int oddBits = maskedNum & 0x55555555; // Bits at odd positions // Check if either even or odd bits are set while the other is not return (evenBits != 0 && oddBits == 0) || (evenBits == 0 && oddBits != 0); } static void Main() { int num, left, right; Console.Write( "Enter the number: " ); num = Convert.ToInt32(Console.ReadLine()); Console.Write( "Enter the left and right range: " ); string [] rangeInput = Console.ReadLine().Split( ' ' ); left = Convert.ToInt32(rangeInput[0]); right = Convert.ToInt32(rangeInput[1]); if (CheckAlternateBits(num, left, right)) { Console.WriteLine( "Yes" ); } else { Console.WriteLine( "No" ); } } } |
Javascript
const readlineSync = require( 'readline-sync' ); // Function to check if alternate bits are set in the given range function checkAlternateBits(num, left, right) { // Create a mask to extract the bits in the specified range let mask = ((1 << (right - left + 1)) - 1) << (left - 1); // Extract the bits in the specified range and shift them to the rightmost positions let maskedNum = (num & mask) >> (left - 1); // Extract even and odd bits using bit masks let evenBits = maskedNum & 0xAAAAAAAA; // Bits at even positions let oddBits = maskedNum & 0x55555555; // Bits at odd positions // Check if either even or odd bits are set while the other is not return (evenBits !== 0 && oddBits === 0) || (evenBits === 0 && oddBits !== 0); } // Main function function main() { let num, left, right; console.log( "Enter the number:" ); num = parseInt(readlineSync.question()); console.log( "Enter the left range:" ); left = parseInt(readlineSync.question()); console.log( "Enter the right range:" ); right = parseInt(readlineSync.question()); if (checkAlternateBits(num, left, right)) { console.log( "Yes" ); } else { console.log( "No" ); } } // Run the main function main(); |
Enter the number: Enter the left and right range: No
time complexity of O(1)
space complexity of O(1)