Search code examples
javascriptloopsfor-loopforeach

How to reverse the digits on a negative number


I am trying to get the output in this way, unfortunately, it isn't return expected value...

function reverseInt(int){
    let intRev ="";
    for(let i= 0; i<int.length; i++){
        intRev = int[i]+intRev ;
    }
    return intRev ;
}
console.log(reverseInt("-12345"));

The desired result is -54321, given the example above.

How do you reverse a string in-place? does not answer the question because the answers are dealing with characters and don't account for the negative sign.


Solution

  • function reverseInt(int){
        const intRev = int.toString().split('').reverse().join('');
        return parseInt(intRev) * Math.sign(int);
    }
    console.log(reverseInt("-12345")); // or alert(reverseInt("-12345"));