DEV Community

NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on • Updated on

Algorithm 101: 3 Ways to Reverse an Integer

This article is a build up on the string reversal article. If you already understand the string reversal algorithm, then all you will find new here is the toString(), Math.sign() and parseInt() methods.


  intReversal(-1234); // -4321

  intReversal(1234); // 4321

Enter fullscreen mode Exit fullscreen mode

Can you try it out on your own?

I will be giving you 3 ways to achieve this.

Prerequisite

To flow with this article, it is expected that you have basic understanding of javascript's string methods, Math methods and array methods.

Let's reverse an integer using:

  • split(), .reverse(), .join(), toString(), parseInt(), Math.sign()
      function intReversal(int) {
        let intToString = int.toString();

        let reversedString = intToString
          .split("")
          .reverse()
          .join("");

        let stringToInt = parseInt(reversedString, 10);

        return stringToInt * Math.sign(int);
      }
Enter fullscreen mode Exit fullscreen mode
  • reduce(), toString(), parseInt(), Math.sign()
      function intReversal(int) {
        let intToString = int.toString();

        let reversedString = [...intToString].reduce((acc, char) => char + acc);

        let stringToInt = parseInt(reversedString, 10);

        return stringToInt * Math.sign(int);
      }
Enter fullscreen mode Exit fullscreen mode
  • for...of...loop, toString(), parseInt(), Math.sign()
      function intReversal(int) {
        let intToString = int.toString();
        let reversedString = "";

        for (char of [...intToString]) {
          reversedString = char + reversedString;
        }

        let stringToInt = parseInt(reversedString, 10);

        return stringToInt * Math.sign(int);
      }
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are many ways to solve problems programmatically. You are only limited by your imagination. Feel free to let me know other ways you solved yours in the comment section.

If you have questions, comments or suggestions, please drop them in the comment section.

Up Next: Algorithm 202: 3 Ways to Sum a Range of Values

You can also follow and message me on social media platforms.

Twitter | LinkedIn | Github

Thank You For Your Time.

Top comments (0)