class Solution {
public int reverse(int x) {
long res = 0;
int tmp = Math.abs(x);
while(tmp > 0){
res = res * 10 + tmp % 10;
if(res > Integer.MAX_VALUE){
return 0;
}
tmp / = 10;
}
return (int)(x>=0?res:-res);
}
}
在看了网上的解法后,自己写了一遍总是不对,后来发现是倒数第二行代码中“/”和“=”之间加了个空格导致的。
解法二(我自己写的)
class Solution {
public int reverse(int x) {
long res = 0;
//int tmp = Math.abs(x);
while(x != 0){
res = res * 10 + x % 10;
if(res > Integer.MAX_VALUE|| res < -Integer.MAX_VALUE){
return 0;
}
x /= 10;
}
return (int)(res);
}
}