DEV Community

Cover image for Solving LeetCode - Reverse Integer
pharia-le
pharia-le

Posted on

Solving LeetCode - Reverse Integer

Question

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: x = 123
Output: 321
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: x = -123
Output: -321
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: x = 120
Output: 21
Enter fullscreen mode Exit fullscreen mode

Example 4:

Input: x = 0
Output: 0
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • -231 <= x <= 231 - 1

Let's Go!

Solve by using PREP.

  • P - One parameter. A number x
  • R - Return the reverse of the number
  • E - Examples provided by question. (See Above)
  • P - See Below
var reverse = function(x) {
    const reversed = x
        .toString()
        .split('')
        .reverse()
        .join('');

    return parseInt(reversed) * Math.sign(x);
};

Enter fullscreen mode Exit fullscreen mode

Translate into code...

var reverse = function(x) {
    // Convert x from number to string
    // Split string into array of elements
    // Apply reverse method
    // Join String
    const reversed = x
        .toString()
        .split('')
        .reverse()
        .join('');

    // Convert string to number & multiple by the sign of x
    // Return the above
    return parseInt(reversed) * Math.sign(x);
};

Enter fullscreen mode Exit fullscreen mode

Conclusion

& Remember... Happy coding, friends! =)

Sources

Top comments (0)