Find smallest number formed by inserting given digit | 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 the string ; Given Input ; Function Call
function MinValue ( N , X ) { let len = N . length ; let position = len + 1 ; if ( N [ 0 ] == ' ' ) { for ( let i = len - 1 ; i >= 1 ; i -- ) { if ( ( N [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) < X ) { position = i ; } } } else { for ( let i = len - 1 ; i >= 0 ; i -- ) { if ( ( N [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) > X ) { position = i ; } } } const c = String . fromCharCode ( X + ' ' . charCodeAt ( 0 ) ) ; let str = N . slice ( 0 , position ) + c + N . slice ( position ) ; return str ; } let N = " " ; let X = 1 ; document . write ( MinValue ( N , X ) ) ;