I want to understand best way to reverse an integer (both positive and negative) in NodeJS 12. Can we do this without converting number to string? It should also support scientific notation numbers like 1e+10 which is 10000000000.
Input/Expected Output
500 = 5
-94 = -49
1234 = 4321
-1 = -1
1e+10 = 1
123.45e+10 = 54321
I hope this one line function solves your use-case
// The Math.sign() function returns either a positive or negative +/- 1,
// indicating the sign of a number passed into the argument.
function reverseInt(n) {
return parseInt(n.toString().split('').reverse().join('')) * Math.sign(n)
}
console.log(reverseInt(500));
console.log(reverseInt(-94));
console.log(reverseInt(1234));
This is the answer I could come up with but I feel there might be better way. I didn't like the way I had to convert the integer to string, reverse it and again convert it back to integer.
parseInt(Math.sign(num) * parseInt(Math.abs(num).toString().split("").reverse().join("")))
function reverseNum(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}