Check if any permutation of a number without any leading zeros is a power of 2 or not | Javascript 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 ; Given Number N ; Function Call
var TEN = 10 ; function updateFreq ( n , freq ) { while ( n ) { var digit = n % TEN ; freq [ digit ] ++ ; n = parseInt ( n / TEN ) ; } } function areAnagrams ( a , b ) { var freqA = Array ( TEN ) . fill ( 0 ) ; var freqB = Array ( TEN ) . fill ( 0 ) ; updateFreq ( a , freqA ) ; updateFreq ( b , freqB ) ; for ( var i = 0 ; i < TEN ; i ++ ) { if ( freqA [ i ] != freqB [ i ] ) return false ; } return true ; } function isPowerOf2 ( N ) { for ( var i = 0 ; i < 32 ; i ++ ) { if ( areAnagrams ( 1 << i , N ) ) { document . write ( ( 1 << i ) ) ; return true ; } } return false ; } var N = 46 ; if ( ! isPowerOf2 ( N ) ) { document . write ( " " ) ; }