Check whether bits are in alternate pattern in the given range | C ++ implementation to check whether bits are in alternate pattern in the given range ; function to check whether bits are in alternate pattern in the given range ; right shift n by ( l - 1 ) bits ; get the bit at the last position in ' num ' ; right shift ' num ' by 1 ; loop until there are bits in the given range ; get the bit at the last position in ' num ' ; if true , then bits are not in alternate pattern ; update ' prev ' ; right shift ' num ' by 1 ; bits are in alternate pattern in the given range ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool bitsAreInAltPatrnInGivenTRange ( unsigned int n , unsigned int l , unsigned int r ) { unsigned int num , prev , curr ; num = n >> ( l - 1 ) ; prev = num & 1 ; num = num >> 1 ; for ( int i = 1 ; i <= ( r - l ) ; i ++ ) { curr = num & 1 ; if ( curr == prev ) return false ; prev = curr ; num = num >> 1 ; } return true ; } int main ( ) { unsigned int n = 18 ; unsigned int l = 1 , r = 3 ; if ( bitsAreInAltPatrnInGivenTRange ( n , l , r ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }