Largest number not exceeding N that does not contain any of the digits of S | Java 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
import java . io . * ; import java . util . Arrays ; class GFG { static String greatestReducedNumber ( String num , String s ) { Boolean [ ] vis_s = new Boolean [ 10 ] ; Arrays . fill ( vis_s , Boolean . FALSE ) ; for ( int i = 0 ; i < ( int ) s . length ( ) ; i ++ ) { vis_s [ ( int ) ( s . charAt ( i ) ) - 48 ] = true ; } int n = num . length ( ) ; int in = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis_s [ ( int ) num . charAt ( i ) - '0' ] ) { in = i ; break ; } } if ( in == - 1 ) { return num ; } for ( char dig = num . charAt ( in ) ; dig >= '0' ; dig -- ) { if ( vis_s [ ( int ) dig - '0' ] == false ) { num = num . substring ( 0 , in ) + dig + num . substring ( in + 1 , n ) ; 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 . charAt ( i ) == '0' ) Count ++ ; else break ; } num = num . substring ( Count , n ) ; if ( ( int ) num . length ( ) == 0 ) return "0" ; return num ; } public static void main ( String [ ] args ) { String N = "12345" ; String S = "23" ; System . out . print ( greatestReducedNumber ( N , S ) ) ; } }