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);
}
}
本文详细介绍了如何通过算法实现整数的反转,并给出了两种不同的实现方式。第一种方法使用绝对值函数,而第二种方法直接处理输入整数。此外,还特别注意了边界条件的处理,确保反转后的结果不会超出整数范围。
2627

被折叠的 条评论
为什么被折叠?



