给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [?231, 231 ? 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
public int reverse(int x) {
//设置为long防止精度溢出
long res = 0;
while (x != 0) {
//取余的规则
// 负数 = 负数 % 正数; 所以不用判断输入的是正数还是负数;
res = x % 10 + res * 10;
x = x / 10;
}
//如果精度溢出就返回0,反之返回res
return (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) ? 0 : (int) res;
}
原文:https://www.cnblogs.com/init-qiancheng/p/14617802.html