Check if any permutation of a number without any leading zeros is a power of 2 or not | Java program for the above approach ; Function to update the frequency array such that freq [ i ] stores the frequency of digit i to n ; While there are digits left to process ; Update the frequency of the current digit ; Remove the last digit ; Function that returns true if a and b are anagrams of each other ; To store the frequencies of the digits in a and b ; Update the frequency of the digits in a ; Update the frequency of the digits in b ; Match the frequencies of the common digits ; If frequency differs for any digit then the numbers are not anagrams of each other ; Function to check if any permutation of a number is a power of 2 or not ; Iterate over all possible perfect power of 2 ; Print that number ; Driver Code ; Given number N ; Function call
import java . util . * ; class GFG { static int TEN = 10 ; static void updateFreq ( int n , int freq [ ] ) { while ( n > 0 ) { int digit = n % TEN ; freq [ digit ] ++ ; n /= TEN ; } } static boolean areAnagrams ( int a , int b ) { int freqA [ ] = new int [ TEN ] ; int freqB [ ] = new int [ TEN ] ; updateFreq ( a , freqA ) ; updateFreq ( b , freqB ) ; for ( int i = 0 ; i < TEN ; i ++ ) { if ( freqA [ i ] != freqB [ i ] ) return false ; } return true ; } static boolean isPowerOf2 ( int N ) { for ( int i = 0 ; i < 32 ; i ++ ) { if ( areAnagrams ( 1 << i , N ) ) { System . out . print ( ( 1 << i ) ) ; return true ; } } return false ; } public static void main ( String [ ] args ) { int N = 46 ; if ( ! isPowerOf2 ( N ) ) { System . out . print ( " No " ) ; } } }