Computer >> Computer tutorials >  >> Programming >> Javascript

Reverse digits of an integer in JavaScript without using array or string methods


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