I recently took a online screening test for a position and one of the problems was inserting a 5 at a position that would maximize the value of the given integer. This was my solution but I scored a 50% on correctness and a 50% on performance. I dont really see where I went wrong or how I could improve it, so I would like some insights on how this is the wrong approach.
function insertDigit(num) {
let neg = num < 0;
let split = neg ? (num * -1).toString().split('').reverse() : num.toString().split('');
let digit = 5;
let i = 0;
while(split[i] > 5){
i++;
}
split.splice( i, 0, "5" );
return neg ? split.reverse().join('') : split.join('');
}
console.log( insertDigit(237) );
Edit: in this example the input is 237 and the expected output is 5237, if it were -237 the expected output would be -2357
/and%) to extract digits. Were you correct with negative numbers? negative numbers are maximized when they are closer to 0.