Title: |
Reverse Integer |
Correct rate: |
34.8% |
Difficulty |
Simple |
Reverse digits of an integer.
EXAMPLE1:X = 123, return 321
example2:x = -123, return-321
Has a thought about this?
Here is some good questions to ask before coding. Bonus points for if you have already thought through this!
If the last digit are 0, what should the output being? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer and then the reverse of 1000000003 overflows. How should handle such cases?
For the purpose of this problem, assume a 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 is the one I feel I can do best! But it took me a long time. The main card is above the cross-border problem,
1, the main problem of cross-border is that the value passed in must not cross the bounds, but after the reversal of the value of the problem will occur across the border.
2, int's boundary problem, because I casually in the online search the next int's bounded by the net wrong answer to confuse. The range of Java int should be 2147483648 to 2147483647 the absolute value of the lower bound is greater than the absolute value of the upper bound
So judging the cross-border is very important!!
The key is how to be quick.
In particular, taking the remainder to save the place and a more brief description of the way
y=y*10+x%10;
And then it's judging positive negative numbers.
This problem is not difficult in general, do not have to talk too much logic directly read the code on the line:
1 Public classSolution {2 Public intReverseintx) {3 intNegative=-1;4 Booleanflag=false;5 if(X<10&&X>-10)returnx;6 if(x==0)return0;7 if(x<0){8X*=-1;9flag=true;Ten } One Longy = x%10; A if(y<0)return0; - while(X/10! = 0 ) { -X/= 10; theY *= 10; -Y + = x%10; - } - if(Y> (Integer.max_value))return0; + if(flag==true){ - return(int) (negative*y); + } A Else at return(int) y; - - } -}
Leetcode------Reverse Integer