public int reverse(int x) {
long rev= 0;
while( x != 0){
rev= rev*10 + x % 10;
x= x/10;
if( rev > Integer.MAX_VALUE  rev < Integer.MIN_VALUE)
return 0;
}
return (int) rev;
}
Very Short (7 lines) and Elegant Solution



@mach7 my way to check overflow is
If(rev /10> Integer.Max ll rev / 10 < Integer.Min)
overflow

i also do this :)
public int reverse(int x) { long result = 0; int digit = 0; while (x != 0) { digit = x % 10; result = (result * 10 + digit); x /= 10; } if(result > Integer.MAX_VALUE  result < Integer.MIN_VALUE){ return 0; } return (int)result; }
I thought last if should be out of the while, so I wrote this ;)


@LLLLLxiaobei
Hi,
Your suggestion is incorrect because rev will be cast to int as well in order to perform an int comparison in the if statement. So, it will be always be equal.Try run the code below as a proof: :)
long r= Integer.MAX_VALUE + 1; if(r == (int)r){ System.out.println("EQUAL, which is wrong"); } else { System.out.println("NOT EQUAL, which is incorrect"); }

@kbakhit said in Very Short (7 lines) and Elegant Solution:
@LLLLLxiaobei
Hi,
Your suggestion is incorrect because rev will be cast to int as well in order to perform an int comparison in the if statement. So, it will be always be equal.Try run the code below as a proof: :)
long r= Integer.MAX_VALUE + 1; if(r == (int)r){ System.out.println("EQUAL, which is wrong"); } else { System.out.println("NOT EQUAL, which is incorrect"); }
The example you gave here is also not appropriate. Here is the reason:
Integer.MAX_VALUE = 2147483647
Integer.MAX_VALUE + 1 = 2147483647 + 1 = 2147483648 = Integer.MIN_VALUEActually, r = Integer.MIN_VALUE, which means r is still in the int range, so "r == (int) r" is true.
