Nearest smaller power of 2 for every digit of a number | Java program to implement the above approach ; 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
import java . util . * ; class GFG { static void highestPowerOfTwo ( int num ) { String s = Integer . toString ( num ) ; for ( int i = 0 ; i < ( int ) s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '0' ) { System . out . print ( "0" ) ; continue ; } int lg = ( int ) ( Math . log ( s . charAt ( i ) - '0' ) / Math . log ( 2 ) ) ; int p = ( int ) Math . pow ( 2 , lg ) ; System . out . print ( ( char ) ( p + 48 ) ) ; } } public static void main ( String args [ ] ) { int num = 4317 ; highestPowerOfTwo ( num ) ; } }