# Detailed Java solution beats 91%

• Here is my detailed solution.
Note this solution beat 91% of solutions once. But when submitted multiple times, on average beats 70% of solutions.
I am new and not sure if different test cases are used each time.
Anyways happy coding. Let me know what you think.

``````class Solution {
public int reverse(int x) {
// long is used to prevent overflowing while computing result in loop.
long result = 0 ;
boolean isNegative = false;
// multiply by -1 to make it positive.
if(x < 0){
isNegative = true;
x *= -1;
}
// reversing the number and saving it in result.
while(x >= 10){
x = (x - numberToAdd) / 10;
result = (result * 10) + numberToAdd;
}
// last digit is added. Or if X is less than 10 (one digit) and while loop is skipped.
result = (result * 10) + x;
if(isNegative){
result *= -1 ;
}
// Since result is long, it could be larger or smaller than MAX and MIN integer value.
if(result <= Integer.MAX_VALUE && result >= Integer.MIN_VALUE ){
return (int)result ;
}else
return 0;
}
}

``````

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