Count remaining array elements after reversing binary representation of each array element | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findReverse ( int N ) { int rev = 0 ; while ( N > 0 ) { rev <<= 1 ; if ( N & 1 == 1 ) rev ^= 1 ; N >>= 1 ; } return rev ; } void countElements ( int arr [ ] , int N ) { vector < int > ans ; for ( int i = 0 ; i < N ; i ++ ) { ans . push_back ( findReverse ( arr [ i ] ) ) ; } unordered_map < int , int > cnt ; for ( int i = 0 ; i < N ; i ++ ) { cnt [ arr [ i ] ] = 1 ; } int count = 0 ; for ( auto i : ans ) { if ( cnt [ i ] ) count ++ ; } cout << count << endl ; } int main ( ) { int arr [ ] = { 1 , 30 , 3 , 8 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countElements ( arr , N ) ; return 0 ; }