7. 整数反转 - LeetCode
7. 整数反转
直接调用Java内置API
class Solution {
public int reverse(int x) {
int coefficient = 1;
if(x < 0){
coefficient = -1;
x *= -1;
}
int ans = 0;
try{
ans = Integer.parseInt(new StringBuilder().append(x).reverse().toString());
} catch(NumberFormatException e){
ans = 0;
} finally{
return coefficient * ans;
}
}
}
这里有几点需要注意:
- 存在负数的情况,若使用字符串反转,则无法处理负号,因此需要提前将系数提出。
- 存在反转后超过int范围的情况,因此需要捕获异常后,设置为0。
这样写法比较简单,但是大材小用,速度有点慢,可以换成自己的反转写法。
自己反转
class Solution {
public int reverse(int x) {
int ans = 0;
while (x != 0) {
int y = x % 10;
x /= 10;
if (ans > Integer.MAX_VALUE/10 || (ans == Integer.MAX_VALUE / 10 && y > 7)){
return 0;
}
if (ans < Integer.MIN_VALUE/10 || (ans == Integer.MIN_VALUE / 10 &&y < -8)){
return 0;
}
ans = ans * 10 + y;
}
return ans;
}
}
自己反转的难点在判断是否溢出。题中要求-231<=x<=231-1,即是有符号整数int的范围,可以与Integer.MAX_VALUE和Integer.MIN_VALUE进行比较。但是溢出就不好比了,所以需要在溢出之前判断下一步是否可能溢出。因为我们是一位一位往上加,所以只需看到231的个位数是8,那么对于正数来说,当前数字与Integer.MAX_VALUE/10比较,如果相同再比较个位数,负数也类似。

浙公网安备 33010602011771号