text: Find smallest number formed by inserting given digit | C ++ 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 the string ; Driver Code ; Given Input ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; string MinValue ( string N , int X ) { int len = N . size ( ) ; int position = len + 1 ; if ( N [ 0 ] == ' - ' ) { for ( int i = len - 1 ; i >= 1 ; i -- ) { if ( ( N [ i ] - '0' ) < X ) { position = i ; } } } else { for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( ( N [ i ] - '0' ) > X ) { position = i ; } } } N . insert ( N . begin ( ) + position , X + '0' ) ; return N ; } int main ( ) { string N = "89" ; int X = 1 ; cout << MinValue ( N , X ) << " STRNEWLINE " ; }