思路
很简单的一道题
所以没啥好说的
class Solution {
public int reverse(int x) {
if(x>0)
{
int temp=0;
try{
while(x>0)
{
temp=temp*10+x%10;
x=x/10;
}
return temp;
}
catch(Exception e){
return 0;
}
}
else
{
int temp=0;
try{
x=x*-1;
while(x>0)
{
temp=temp*10+x%10;
x=x/10;
}
return temp*-1;
}
catch(Exception e){
return 0;
}
}
}
}
其实小于0大于0可以合并没有影响
class Solution {
public int reverse(int x) {
long temp=0;
try{
while(x!=0)
{
temp=temp*10+x%10;
x=x/10;
}
return (int)temp;
}
catch(Exception e){
return 0;
}
}
}
但是这个try-catch模块在这里用不了为什么呢
因为java中一旦发生整数溢出,他会自动回来,反正就拿这个测试用例来看
其实通过的相当多,就是差那么几个
特殊的
就会有问题
class Solution {
public int reverse(int x) {
// 定义变量来存储反转后的整数
long temp = 0; // 使用long类型以避免在while循环中发生溢出
while (x != 0) {
temp = temp * 10 + x % 10;
x = x / 10;
// 检查是否超出32位有符号整数范围
if (temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) {
return 0;
}
}
// 将long类型转换回int类型
return (int) temp;
}
}
这个才是正确的
诶其实try-catch也能用不过看具体情况
只能说不知道了
麻了