Reversing Negative and Positive Numbers in JavaScript



Problem

We are required to write a JavaScript function that takes in a number and returns its reversed number.

One thing that we should keep in mind is that numbers should preserve their sign; i.e., a negative number should still be negative when reversed.

Example

Following is the code −

 Live Demo

const num = -224;
function reverseNumber(n) {
   let x = Math.abs(n)
   let y = 0
   while (x > 0) {
      y = y * 10 + (x % 10)
      x = Math.floor(x / 10)
   };
   return Math.sign(n) * y
};
console.log(reverseNumber(num));

Output

-422
Updated on: 2021-04-17T12:27:34+05:30

944 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements