Maximum Value after Insertion LeetCode solution in JavaScript

1
var maxValue = function (n, x) {
2
let i;
3

4
// if the number if positive, find the first
5
// number that is less than x
6
if (n[0] !== "-") {
7
for (i = 0; i < n.length; i++) {
8
if (Number(n[i]) < x) break;
9
}
10

11
// if the number is negative, find the first
12
// number that is greater than x
13
} else {
14
for (i = 1; i < n.length; i++) {
15
if (Number(n[i]) > x) break;
16
}
17
}
18

19
// return the string with x inserted at the found index
20
return n.slice(0, i) + x + n.slice(i);
21
};
22

23
///////////////// short hand ////////////////////
24

25
var maxValue = function (n, x) {
26
let i;
27
if (n[0] !== "-") {
28
for (i = 0; i < n.length; i++) {
29
if (Number(n[i]) < x) break;
30
}
31
} else {
32
for (i = 1; i < n.length; i++) {
33
if (Number(n[i]) > x) break;
34
}
35
}
36
return n.slice(0, i) + x + n.slice(i);
37
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0