Reversing negative and positive numbers in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 17-Apr-2021 12:04:50
Advertisements