Nearest smaller power of 2 for every digit of a number | Function to find the nearest power of two for every digit of a given number ; Converting number to string ; Traverse the array ; Calculate log base 2 of the current digit s [ i ] ; Highest power of 2 <= s [ i ] ; ASCII conversion ; Driver Code
function highestPowerOfTwo ( num ) { var s = num . toString ( ) ; for ( var i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] === " " ) { document . write ( " " ) ; continue ; } var lg = parseInt ( Math . log2 ( s [ i ] . charCodeAt ( 0 ) - 48 ) ) ; var p = Math . pow ( 2 , lg ) ; document . write ( String . fromCharCode ( p + 48 ) ) ; } } var num = 4317 ; highestPowerOfTwo ( num ) ;