Minimum number of distinct powers of 2 required to express a given binary number | Function to return the minimum distinct powers of 2 required to express s ; Reverse the string to start from lower powers ; Check if the character is 1 ; Add in range provided range ; Initialize the counter ; Check if the character is not 0 ; Increment the counter ; Print the result ; Driver Code
def findMinimum ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE x = [ 0 ] * ( n + 1 ) NEW_LINE s = s [ : : - 1 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT if ( x [ i ] == 1 ) : NEW_LINE INDENT x [ i + 1 ] = 1 NEW_LINE x [ i ] = 0 NEW_LINE DEDENT elif ( i and x [ i - 1 ] == 1 ) : NEW_LINE INDENT x [ i + 1 ] = 1 NEW_LINE x [ i - 1 ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT x [ i ] = 1 NEW_LINE DEDENT DEDENT DEDENT c = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( x [ i ] != 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT print ( c ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "111" NEW_LINE findMinimum ( str ) NEW_LINE DEDENT