Find the number in a range having maximum product of the digits | CPP 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 ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int product ( int x ) { int prod = 1 ; while ( x ) { prod *= ( x % 10 ) ; x /= 10 ; } return prod ; } int findNumber ( int l , int r ) { string a = to_string ( l ) ; string b = to_string ( r ) ; int ans = r ; for ( int i = 0 ; i < b . size ( ) ; i ++ ) { if ( b [ i ] == '0' ) continue ; string curr = b ; curr [ i ] = ( ( curr [ i ] - '0' ) - 1 ) + '0' ; for ( int j = i + 1 ; j < curr . size ( ) ; j ++ ) curr [ j ] = '9' ; int num = 0 ; for ( auto c : curr ) num = num * 10 + ( c - '0' ) ; if ( num >= l && product ( ans ) < product ( num ) ) ans = num ; } return ans ; } int main ( ) { int l = 1 , r = 10 ; cout << findNumber ( l , r ) << endl ; l = 51 , r = 62 ; cout << findNumber ( l , r ) << endl ; return 0 ; }