Modify string by sorting characters after removal of characters whose frequency is not equal to power of 2 | C ++ program for the above approach ; Function to remove all the characters from a string that whose frequencies are not equal to a perfect power of 2 ; Stores the frequency of each character in S ; Iterate over characters of string ; Update frequency of current character in the array freq [ ] ; Traverse the array freq [ ] ; Check if the i - th letter is absent from string S ; Calculate log of frequency of the current character in the string S ; Calculate power of 2 of lg ; Check if freq [ i ] is a power of 2 ; Print letter i + ' a ' freq [ i ] times ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countFrequency ( string S , int N ) { int freq [ 26 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { freq [ S [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == 0 ) continue ; int lg = log2 ( freq [ i ] ) ; int a = pow ( 2 , lg ) ; if ( a == freq [ i ] ) { while ( freq [ i ] -- ) cout << ( char ) ( i + ' a ' ) ; } } } int main ( ) { string S = " aaacbb " ; int N = S . size ( ) ; countFrequency ( S , N ) ; return 0 ; }