Find the number in a range having maximum product of the digits | Returns the product of digits of number x ; This function returns the number having maximum product of the digits ; Converting both integers to strings ; Let the current answer be r ; Stores the current number having current digit one less than current digit in b ; Replace all following digits with 9 to maximise the product ; Convert string to number ; Check if it lies in range and its product is greater than max product ; Driver Code
def product ( x ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( x ) : NEW_LINE INDENT prod *= ( x % 10 ) NEW_LINE x //= 10 ; NEW_LINE DEDENT return prod NEW_LINE DEDENT def findNumber ( l , r ) : NEW_LINE INDENT a = str ( l ) ; NEW_LINE b = str ( r ) ; NEW_LINE ans = r NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT if ( b [ i ] == '0' ) : NEW_LINE INDENT continue NEW_LINE DEDENT curr = list ( b ) NEW_LINE curr [ i ] = str ( ( ( ord ( curr [ i ] ) - ord ( '0' ) ) - 1 ) + ord ( '0' ) ) NEW_LINE for j in range ( i + 1 , len ( curr ) ) : NEW_LINE INDENT curr [ j ] = str ( ord ( '9' ) ) NEW_LINE DEDENT num = 0 NEW_LINE for c in curr : NEW_LINE INDENT num = num * 10 + ( int ( c ) - ord ( '0' ) ) NEW_LINE DEDENT if ( num >= l and product ( ans ) < product ( num ) ) : NEW_LINE INDENT ans = num NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l , r = 1 , 10 NEW_LINE print ( findNumber ( l , r ) ) NEW_LINE l , r = 51 , 62 NEW_LINE print ( findNumber ( l , r ) ) NEW_LINE DEDENT