Leetcode reverse Integer, because the maximum value of int is 2 minus one, and the minimum value is 31 times of 2.
My first code put the res recursively in the try and thought there would be an exception to the overflow, but not.
Because the arguments that are passed in are of type int, and the memory and time requirements are met, long is sufficient to store the intermediate result. There's a guy on leet with a more witty overflow test (see for yourself: D)
My Code:
Public classSolution { Public intReverseintx) {if(x<=9&&x>=-9| | X==0){ returnx; } BooleanNagetive=false; inty=x; if(x<0) {y=-x; Nagetive=true; } arraydeque<Integer> s=NewArraydeque (); while(y>0) {S.add (y%10); Y/=10; } Longres=0l; while(S.size () >=1) {res+=s.poll () *math.pow (10, S.size ()); } if(res>integer.max_value| | res<integer.min_value) { return0; } returnNagetive? (int)-res: (int) Res; }}
Add method for overflow detection in Java 8.
Stack overflow:https://stackoverflow.com/questions/3001836/ How-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo
Java integer addition subtration Overflow integer plus minus overflow