Reverse Integer is a very interesting algorithm question asked in many interviews including FAANG companies.  

This can be solved by using javascript functions but we will not be going to use them because we will be making an algorithm for it and companies ask for algorithms, not pre-defined functions.

The question for an algorithm is, 


Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).


Example 1:

Input: x = 123

Output: 321


Example 2:

Input: x = -123

Output: -321


Example 3:

Input: x = 120

Output: 21


Constraints

-231 <= x <= 231 - 1


Let's start with the algorithm,


var reverse = function(x) {

    var c=x;

  // convert negative to a positive integer

    c=((x > 0)? 1:-1)*c;

    var result='';

    while(c > 0)

    {

    result=result + c % 10;

       // Math.floor is used to convert (1.2 to 1 or 23.6 to 23)

    c=Math.floor(c/10);

    }

   // 2147483647 = 231 - 1

    if (result > 2147483647) { return 0 }

   // (x > 0)?1:-1) is used to convert result to negative if integer x is negative. 

    return ((x > 0)? 1:-1)*result;

};


Here, we stored x integer into variable c after that we used this ((x > 0)? 1:-1)*c to convert c to a positive integer based on x. We have checked in the while loop till the number c becomes less than zero.

In the while loop, we store the remainder of c%10 to result in a variable combined with the previous result. 

c=Math.floor(c/10) is used to just remove the last number from the value ( 342/10 = 34.2, Math.floor(34.2) = 34). 

Then we compared (result > 2147483647) results with 231 - 1.

In the final return, we just converted the result back to negative or positive based on x.


I hope you understood the algorithm, if you have any doubts please let us know in the comments.