Find smallest number formed by inserting given digit | Java implementation of above approach ; Function to insert X in N and return the minimum value string ; Variable to store length of string N ; Variable to denote the position where X must be added ; If the given string N represent a negative value ; X must be place at the last index where is greater than N [ i ] ; For positive numbers , X must be placed at the last index where it is smaller than N [ i ] ; Insert X at that position ; return string ; Driver call ; given input ; function call
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static String MinValue ( String number , int x ) { int length = number . length ( ) ; int position = length + 1 ; if ( number . charAt ( 0 ) == ' - ' ) { for ( int i = number . length ( ) - 1 ; i >= 1 ; -- i ) { if ( ( number . charAt ( i ) - 48 ) < x ) { position = i ; } } } else { for ( int i = number . length ( ) - 1 ; i >= 0 ; -- i ) { if ( ( number . charAt ( i ) - 48 ) > x ) { position = i ; } } } number = number . substring ( 0 , position ) + x + number . substring ( position , number . length ( ) ) ; return number . toString ( ) ; } public static void main ( String [ ] args ) { String number = "89" ; int x = 1 ; System . out . print ( MinValue ( number , x ) ) ; } }