Count remaining array elements after reversing binary representation of each array element | Java program for the above approach ; Function to reverse the binary representation of a number ; Traverse bits of N from the right ; Bitwise left shift ' rev ' by 1 ; If current bit is '1' ; Bitwise right shift N by 1 ; Required number ; Function to count elements from the original array that are also present in the array formed by reversing the binary representation of each element ; Stores the reversed num ; Iterate from [ 0 , N ] ; Stores the presence of integer ; Stores count of elements present in original array ; Traverse the array ; If current number is present ; Print the answer ; Driver code
import java . util . * ; public class GFG { static int findReverse ( int N ) { int rev = 0 ; while ( N > 0 ) { rev <<= 1 ; if ( ( N & 1 ) == 1 ) rev ^= 1 ; N >>= 1 ; } return rev ; } static void countElements ( int arr [ ] , int N ) { Vector < Integer > ans = new Vector < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { ans . add ( findReverse ( arr [ i ] ) ) ; } HashMap < Integer , Integer > cnt = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { cnt . put ( arr [ i ] , 1 ) ; } int count = 0 ; for ( Integer i : ans ) { if ( cnt . containsKey ( i ) ) count ++ ; } System . out . println ( count ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 30 , 3 , 8 , 12 } ; int N = arr . length ; countElements ( arr , N ) ; } }