Modify string by sorting characters after removal of characters whose frequency is not equal to power of 2 | Java 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
class GFG { static void countFrequency ( String S , int N ) { int [ ] freq = new int [ 26 ] ; Array . Clear ( freq , 0 , freq . Length ) ; for ( int i = 0 ; i < N ; i ++ ) { freq [ ( int ) S . charAt ( i ) - ' a ' ] += 1 ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == 0 ) continue ; int lg = ( int ) ( Math . log ( freq [ i ] ) / Math . log ( 2 ) ) ; int a = ( int ) Math . pow ( 2 , lg ) ; if ( a == freq [ i ] ) { while ( freq [ i ] > 0 ) { freq [ i ] -= 1 ; System . out . print ( ( char ) ( i + ' a ' ) ) ; } } } } public static void main ( String args [ ] ) { String S = " aaacbb " ; int N = S . length ( ) ; countFrequency ( S , N ) ; } }