[Leetcode] Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x =-123, return-321
Click to show 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 shoshould the output be? Ie, cases such as 10,100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How can you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10 ):
Test cases had been added to test the overflow behavior.
This question was updated in November 10 with a test case of Anti-transfer overflow. Therefore, we need to find this part of the number, and then kill it, and return 0.
The previous AC code is not updated here for you to familiarize yourself with your ideas.
class Solution {public: int reverse(int x) { int flag = (x > 0) ? 1:-1; int y =abs(x); int result = 0; while(y){ result = result*10 + y%10; y = y/10; } return flag*result; }};The idea is very simple. It is to add the last digit to the result and multiply it by 10. In this way, the highest bit of the original number is obtained and added to the result. The highest bit of the result is the lowest Bit of the original number.
But now the problem arises. If the reverse number of the original number overflows, it will be wrong.
Now, if the obtained reverse number is larger than INT_MAX, it will overflow, and this number will change in the memory, so it cannot be compared with the size of INT_MAX. So here is another way of thinking. Compare the result in the previous step with the size of INT_MAX/10. If the result in a step is larger than INT_MAX/10 and y> 0, the result will overflow.
This code is AC, but think about how many spies will come in. If there is a number, the result of the second flip result = INT_MAX/10, and the highest position y> INT_MAX % 10 will also overflow, so you may need to exclude this part.
In fact, this method is to install a patch on the original method, and there is no better solution.
Another one is that INT_MIN needs to be excluded. This product is 1 larger than INT_MAX after the absolute value is obtained, which directly overflows.
class Solution {public: int reverse(int x) { if(x == INT_MIN) return false; int flag = (x > 0) ? 1:-1; int y =abs(x); int result = 0; while(y){ result = result*10 + y%10; y = y/10; if(result>(INT_MAX/10)&&y > 0 || result==(INT_MAX/10)&&y>INT_MAX%10) return false; } return flag*result; }};
I hope you can give me some suggestions. If you think of a better method, please let me know.