Maximum Value after Insertion LeetCode solution in Java
1class Solution {2public String maxValue(String n, int x) {3StringBuilder res = new StringBuilder();4int i = 0, j = 0;5if (n.charAt(0) == '-') {6res.append(n.charAt(0));7for (j = 1; j < n.length(); j++) {8char ch = n.charAt(j);9int val = ch - '0';10if (val <= x) {11res.append(ch);12} else {13res.append(x);14res.append(ch);15res.append(n.substring(j + 1));16break;17}18}19if (j == n.length()) {20res.append(x);21}22} else {23for (i = 0; i < n.length(); i++) {24char ch = n.charAt(i);25int val = ch - '0';2627if (val >= x) {28res.append(ch);29} else {30res.append(x);31res.append(ch);32res.append(n.substring(i + 1));33break;34}35}36if (i == n.length()) {37res.append(x);38}39}40return res.toString();41}42}