Maximum Value after Insertion LeetCode solution in Java

1
class Solution {
2
public String maxValue(String n, int x) {
3
StringBuilder res = new StringBuilder();
4
int i = 0, j = 0;
5
if (n.charAt(0) == '-') {
6
res.append(n.charAt(0));
7
for (j = 1; j < n.length(); j++) {
8
char ch = n.charAt(j);
9
int val = ch - '0';
10
if (val <= x) {
11
res.append(ch);
12
} else {
13
res.append(x);
14
res.append(ch);
15
res.append(n.substring(j + 1));
16
break;
17
}
18
}
19
if (j == n.length()) {
20
res.append(x);
21
}
22
} else {
23
for (i = 0; i < n.length(); i++) {
24
char ch = n.charAt(i);
25
int val = ch - '0';
26

27
if (val >= x) {
28
res.append(ch);
29
} else {
30
res.append(x);
31
res.append(ch);
32
res.append(n.substring(i + 1));
33
break;
34
}
35
}
36
if (i == n.length()) {
37
res.append(x);
38
}
39
}
40
return res.toString();
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0