Find the occurrence of the given binary pattern in the binary representation of the array elements | C ++ implementation of the approach ; Function to return the binary representation of n ; Array to store binary representation ; Counter for binary array ; Storing remainder in binary array ; To store the binary representation as a string ; Function to return the frequency of pat in the given string txt ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; If pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Function to find the occurrence of the given pattern in the binary representation of elements of arr [ ] ; For every element of the array ; Find its binary representation ; Print the occurrence of the given pattern in its binary representation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string decToBinary ( int n ) { int binaryNum [ 32 ] ; int i = 0 ; while ( n > 0 ) { binaryNum [ i ] = n % 2 ; n = n / 2 ; i ++ ; } string binary = " " ; for ( int j = i - 1 ; j >= 0 ; j -- ) binary += to_string ( binaryNum [ j ] ) ; return binary ; } int countFreq ( string & pat , string & txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int res = 0 ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { res ++ ; j = 0 ; } } return res ; } void findOccurrence ( int arr [ ] , int n , string pattern ) { for ( int i = 0 ; i < n ; i ++ ) { string binary = decToBinary ( arr [ i ] ) ; cout << countFreq ( pattern , binary ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , 106 , 7 , 8 } ; string pattern = "10" ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findOccurrence ( arr , n , pattern ) ; return 0 ; }