# [2 ms JAVA] Better way to handle overflow/underflow and a simple solution

• This solution would work if you have been allowed to use 64 bits instead of 32 bit

``````public class Solution {
static int max = Integer.MAX_VALUE;
static int min = Integer.MIN_VALUE;
public int reverse(int x) {
int r = 0;
if(x>1000000000 && x%10>2) return 0; // optimization only for 32 bit
if(x< -1000000000 && x%10<-2) return 0; // optimization only for 32 bit
while(x != 0)
{
if((r*10)/10 != r) return 0; // check overflow without long
r = r*10 + x%10;
x = x/10;
}
return r;
}}``````

• could you explain the two statements given by you for optimization? thanks!

• This optimization is nothing but a fast way to check if the reverse of the given value will underflow/overflow.

How it works?

Let's take a basic example:
x = 1000000003
it would satisfy x>1000000000
and when reversed it would overflow (3000000001)

We can check most of the cases if they over/underflow without going into the loop
Mind you that this would only work for 32 bit integers, for long you might have to remove/change this optimization.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.