Largest number not exceeding N that does not contain any of the digits of S | C # program to implement the above approach ; Function to obtain the largest number not exceeding num which does not contain any digits present in S ; Stores digits of S ; Traverse the string S ; Set occurrence as true ; Traverse the string n ; All digits of num are not present in string s ; Largest Digit not present in the string s ; Set all digits from positions in + 1 to n - 1 as LargestDig ; Counting leading zeroes ; Removing leading zeroes ; If the string becomes null ; Return the largest number ; Driver code
using System ; using System . Collections . Generic ; class GFG { static string greatestReducedNumber ( string num , string s ) { bool [ ] vis_s = new bool [ 10 ] ; for ( int i = 0 ; i < ( int ) s . Length ; i ++ ) { vis_s [ ( int ) ( s [ i ] ) - 48 ] = true ; } int n = num . Length ; int In = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis_s [ ( int ) num [ i ] - '0' ] ) { In = i ; break ; } } if ( In == - 1 ) { return num ; } for ( char dig = num [ In ] ; dig >= '0' ; dig -- ) { if ( vis_s [ ( int ) dig - '0' ] == false ) { num = num . Substring ( 0 , In ) + dig + num . Substring ( In + 1 , n - In - 1 ) ; break ; } } char LargestDig = '0' ; for ( char dig = '9' ; dig >= '0' ; dig -- ) { if ( vis_s [ dig - '0' ] == false ) { LargestDig = dig ; break ; } } for ( int i = In + 1 ; i < n ; i ++ ) { num = num . Substring ( 0 , i ) + LargestDig ; } int Count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( num [ i ] == '0' ) Count ++ ; else break ; } num = num . Substring ( Count , n ) ; if ( ( int ) num . Length == 0 ) return "0" ; return num ; } static void Main ( ) { string N = "12345" ; string S = "23" ; Console . Write ( greatestReducedNumber ( N , S ) ) ; } }