Reverse Digits of an Integer in JavaScript



We are required to write Number.prototype.reverse() function that returns the reversed number of the number it is used with.

For example −

234.reverse() = 432;
6564.reverse() = 4656;

Let’s write the code for this function. We will use a recursive approach like this −

Example

const reverse = function(temp = Math.abs(this), reversed = 0, isNegative =
this < 0){
   if(temp){
      return reverse(Math.floor(temp/10), (reversed*10)+temp%10,isNegative);
   };
   return !isNegative ? reversed : reversed*-1;
};
Number.prototype.reverse = reverse;
const n = -12763;
const num = 43435;
console.log(num.reverse());
console.log(n.reverse());

Output

The output in the console will be −

53434
-36721
Updated on: 2020-08-21T13:18:25+05:30

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements