1,翻转每一位数字即可,原理比较简单,我们直接来看图分析
public int reverse(int x) {
int res = 0;
while (x != 0) {
int t = x % 10;
int newRes = res * 10 + t;
//如果数字溢出,直接返回0
if ((newRes - t) / 10 != res)
return 0;
res = newRes;
x = x / 10;
}
return res;
}
2,实际上我们还可以改的更简洁一下
public int reverse(int x) {
long res = 0;
while (x != 0) {
res = res * 10 + x % 10;
x /= 10;
}
return (int) res == res ? (int) res : 0;
}