Find the number in a range having maximum product of the digits | Java Program to 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 string a = l . ToString ( ) ; ; 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
class GFG { static int product ( int x ) { int prod = 1 ; while ( x > 0 ) { prod *= ( x % 10 ) ; x /= 10 ; } return prod ; } static int findNumber ( int l , int r ) { String b = Integer . toString ( r ) ; int ans = r ; for ( int i = 0 ; i < b . length ( ) ; i ++ ) { if ( b . charAt ( i ) == '0' ) continue ; char [ ] curr = b . toCharArray ( ) ; curr [ i ] = ( char ) ( ( ( int ) ( curr [ i ] - ( int ) '0' ) - 1 ) + ( int ) ( '0' ) ) ; for ( int j = i + 1 ; j < curr . length ; j ++ ) curr [ j ] = '9' ; int num = 0 ; for ( int j = 0 ; j < curr . length ; j ++ ) num = num * 10 + ( curr [ j ] - '0' ) ; if ( num >= l && product ( ans ) < product ( num ) ) ans = num ; } return ans ; } public static void main ( String [ ] args ) { int l = 1 , r = 10 ; System . out . println ( findNumber ( l , r ) ) ; l = 51 ; r = 62 ; System . out . println ( findNumber ( l , r ) ) ; } }