Find array elements with rightmost set bit at the position of the rightmost set bit in K | C ++ program for the above approach ; Function to find the mask for finding rightmost set bit in K ; Function to find all array elements with rightmost set bit same as that in K ; Stores mask of K ; Store position of rightmost set bit ; Traverse the array ; Check if rightmost set bit of current array element is same as position of rightmost set bit in K ; Driver Code ; Input ; Function call to find the elements having same rightmost set bit as of K
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int findMask ( int K ) { int mask = 1 ; while ( ( K & mask ) == 0 ) { mask = mask << 1 ; } return mask ; } void sameRightSetBitPos ( int arr [ ] , int N , int K ) { int mask = findMask ( K ) ; int pos = ( K & mask ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( arr [ i ] & mask ) == pos ) cout << arr [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 3 , 4 , 6 , 7 , 9 , 12 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 7 ; sameRightSetBitPos ( arr , N , K ) ; return 0 ; }