 Open in App
Not now

# Print the largest integer formed by inserting digit X in given string

• Last Updated : 10 Sep, 2022

Given a string S of size N representing a large integer value, and a positive digit X, the task is to print the largest integer formed by inserting the digit X in the string S.

Examples:

Input: S = “99”, X = 9
Output: 999
Explanation:
The largest number that can be formed is 999 after inserting 9 into “99”.

Input: S = “-13”, X = 2
Output: -123
Explanation:
The largest number that can be formed is -123 after inserting 2 into “-13”.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The problem can be solved by iterating over the character of the string S. Follow the steps below to solve this problem:

• If the number S is positive, then perform the following steps:
• Iterate in the range [0,  N-1] using the variable i and perform the following steps:
• If S[i] is less than X then insert the digit X before S[i] and break the loop.
• If none of the above cases satisfy, then append the digit X at the end of the string S.
• Else, if the number S is negative, then perform the following steps:
• Iterate in the range [0, N-1] in using the variable i and perform the following steps:
• If S[i] is less than X, then insert the digit X before S[i] and break the loop.
• If none of the above cases satisfy, then append the digit X at the end of the string S.
• Finally, print the largest possible string, represented by S.

Below is the implementation of the above approach:

## Python3

 `# Python program for the above approach` `# Function to find Largest Number after``# insertion of a digit``def` `largestValue(S, X):` `    ``# If S is negative``    ``if` `S[``0``] ``=``=` `'-'``:``        ``f ``=` `0``        ``# Iterate through characters of S``        ``for` `i, val ``in` `enumerate``(S):``            ``if` `i ``=``=` `0``:``                ``continue` `            ``# If digit x is less``            ``# than S[i] insert digit``            ``# after X``            ``if` `X < ``int``(val):``                ``f ``=` `1``                ``S ``=` `S[:i] ``+` `str``(X) ``+` `S[i:]``                ``break` `        ``if` `f ``=``=` `0``:``            ``S ``=` `S ``+` `str``(X)` `    ``# If S is positive``    ``else``:``        ``f ``=` `0` `        ``# If x > S[i] insert x``        ``for` `i, val ``in` `enumerate``(S):``            ``if` `X > ``int``(val):``                ``f ``=` `1``                ``S ``=` `S[:i] ``+` `str``(X) ``+` `S[i:]``                ``break` `        ``if` `f ``=``=` `0``:``            ``S ``=` `S ``+` `str``(X)` `    ``# Return the answer``    ``return` `S`  `# Driver Code` `# Given Input``S ``=` `"-13"``X ``=` `2` `# Function Call``print``(largestValue(S, X))`

Output

`-123`

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up