Maximize the number N by inserting given digit at any position | C ++ program for the above approach ; Function to find the maximum value of N after inserting the digit K ; Convert it into N to string ; Stores the maximum value of N after inserting K ; Iterate till all digits that are not less than K ; Add the current digit to the string result ; Add digit ' K ' to result ; Iterate through all remaining characters ; Add current digit to result ; Print the maximum number formed ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximizeNumber ( int N , int K ) { string s = to_string ( N ) ; int L = s . length ( ) ; string result ; int i = 0 ; while ( ( i < L ) && ( K <= ( s [ i ] - '0' ) ) ) { result . push_back ( s [ i ] ) ; ++ i ; } result . push_back ( char ( K + '0' ) ) ; while ( i < L ) { result . push_back ( s [ i ] ) ; ++ i ; } cout << result ; } int main ( ) { int N = 6673 , K = 6 ; maximizeNumber ( N , K ) ; return 0 ; }