题目:
思路
很容易想到先取10 的余,得到最后一位上的数,再除10,将最后一位抛弃。
易错:反转之后,容易超出int类型范围:
int表示范围:
(-2^31,
2^31 -1)
-2^31最后一位是8
2^31 -1最后一位是7
class Solution {
public int reverse(int x) {
int ans = 0;
while(x != 0) {
int pop = x % 10;
x = x / 10;
if(ans > Integer.MAX_VALUE/10 || (ans == Integer.MAX_VALUE/10 && pop > 7)) return 0;
if(ans < Integer.MIN_VALUE/10 || (ans == Integer.MIN_VALUE/10 && pop < -8)) return 0;
ans = ans*10 + pop;
}
return ans;
}
}