Find array elements with rightmost set bit at the position of the rightmost set bit in K | Java 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
import java . io . * ; class GFG { static int findMask ( int K ) { int mask = 1 ; while ( ( K & mask ) == 0 ) { mask = mask << 1 ; } return mask ; } public static void sameRightSetBitPos ( int [ ] arr , int N , int K ) { int mask = findMask ( K ) ; final int pos = ( K & mask ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( arr [ i ] & mask ) == pos ) System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 4 , 6 , 7 , 9 , 12 , 15 } ; int N = arr . length ; int K = 7 ; sameRightSetBitPos ( arr , N , K ) ; } }