[English ver]Easy
7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = 123, return 321
Note:
The input is assumed to be a 32bit signed integer. Your function should return 0 when the reversed integer overflows.
spoilers
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Approach 1 use StringBuilder:


Analysis
This approach turn Integer to a positive Integer and reverse it with StringBuilder. use try catch to deal with the overflows . if the input is negative , we can change the result to negative in last.
Time complexity ： O(n) 。n is the digit of the x
Space complexity ： O(1) .
Approach 2 use int:


or


Analysis
These two Solution has the same principle . They use the input x%10 to get the remainder which is the last digit of the x, and then use result*10 to add a digit to result and update the last digit to the x%10 , after that update x to x/10.
The only difference of the two solution is the way to judge the result is overflows or not. Solution1 is use the new result remove last digit campare to the old result,if they are equals to each other there is not overflows,else there is overflows. In other side , Solution2 is use the new result compare to the Integer’s limit threshold ,if it didn’t out of the threshold ,there is not overflows,else there is a overflows, notice that , long rev = 0; in the code,your can;t use Integer to replace it , because once Integer overflows,java will change the value to make it between the limit threshold of the Integer. So rev > Integer.MAX_VALUE  rev < Integer.MIN_VALUE will never be true.
Time complexity ： O(n) 。n is the digit of the x.
Space complexity ： O(1) .
If you have any suggestions to make the logic and implementation more better , or you have some advice on my description. Please let me know!Thanks!
About Me
My blog leonchen1024.com
My Github https://github.com/LeonChen1024
My twitter https://twitter.com/LChen1024?lang=en