Nearest smaller power of 2 for every digit of a number | Python 3 program for 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 math NEW_LINE def highestPowerOfTwo ( num ) : NEW_LINE INDENT s = str ( num ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT print ( "0" ) NEW_LINE continue NEW_LINE DEDENT lg = int ( math . log2 ( ord ( s [ i ] ) - 48 ) ) NEW_LINE p = pow ( 2 , lg ) NEW_LINE print ( chr ( p + 48 ) , end = " " ) NEW_LINE DEDENT DEDENT num = 4317 NEW_LINE highestPowerOfTwo ( num ) NEW_LINE