LeetCode #7 – Reverse Integer

The next question that I decided to tackle was:

While it seems like quite a simple problem to just reverse the digits, it requires a bit of thinking on how to implement it. Here are some examples of input and output for this problem:

So, it is a pretty self explanatory question and solution. What I did was I created a temporary long variable, output, which I would eventually return as the output for the method. I also created a while loop to take the end of the original number(input) and add it to the beginning of the output variable. Here is how I achieved that:

After that, all we need to do is check to make sure that the output variable is within the constraints of a 32-bit integer. If it isn’t, then I would return 0. Here is what that looks like:

If it is within the constraints, I cast the long output variable as an integer by doing this:

Here is the whole solution:

Here is my output:

Here are the logistics of my solution:

That’s the second 100% in a row! While not exactly ideal for memory usage, it still gets the job done. If you have any suggestions, be sure to let me know in the comments section below. I hope you guys at least learned something today, and that you all have a great day!

By:

Posted in:


Leave a comment