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 ; Let the current answer be r ; Converting both integers to strings ; 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
< ? php function product ( $ x ) { $ prod = 1 ; while ( $ x ) { $ prod *= ( $ x % 10 ) ; $ x = ( int ) ( $ x / 10 ) ; } return $ prod ; } function findNumber ( $ l , $ r ) { $ ans = $ r ; $ a = strval ( $ l ) ; $ b = strval ( $ r ) ; for ( $ i = 0 ; $ i < strlen ( $ b ) ; $ i ++ ) { if ( $ b [ $ i ] == '0' ) continue ; $ curr = $ b ; $ curr [ $ i ] = chr ( ( ( ord ( $ curr [ $ i ] ) - ord ( '0' ) ) - 1 ) + ord ( '0' ) ) ; for ( $ j = $ i + 1 ; $ j < strlen ( $ curr ) ; $ j ++ ) $ curr [ $ j ] = '9' ; $ num = 0 ; for ( $ c = 0 ; $ c < strlen ( $ curr ) ; $ c ++ ) $ num = $ num * 10 + ( ord ( $ curr [ $ c ] ) - ord ( '0' ) ) ; if ( $ num >= $ l and product ( $ ans ) < product ( $ num ) ) $ ans = $ num ; } return $ ans ; } $ l = 1 ; $ r = 10 ; print ( findNumber ( $ l , $ r ) . " " ) ; $ l = 51 ; $ r = 62 ; print ( findNumber ( $ l , $ r ) ) ; ? >