public class Solution {
public int reverse(int x) {
int result = 0;
int flag = x<0?1:1;
x=x*flag;
while (x>0){
// after the multiply is should not exceed
if(Integer.MAX_VALUE/10<result){
return 0;
}
// after the multiply and the increase, it should not exceed
if(Integer.MAX_VALUE result*10 < (x%10)){
return 0;
}
result = (x%10)+result*10;
x/=10;
}
return result*flag;
}
}
Javasimplefasto(n)noconvert


Similar thought, but avoid the overflow caused by Integer.MIN_VALUE.
public class Solution { public int reverse(int x) { boolean negative = false; int res = 0; if(x < 0) { if(x == Integer.MIN_VALUE) return 0; x = x; negative = true; } while(x / 10 != 0) { res = 10 * res + x % 10; if(res > Integer.MAX_VALUE / 10) return 0; x /= 10; } res = 10 * res + x; return negative ? res : res; } }