我试图反转一个整数,但有一个条件。如果整数a不适合32位有符号整数值,则函数应返回0.我正在处理该情况,但程序引发异常。为什么?
public class Solution {
public int reverse(int a) {
String s = Integer.toString(a);
StringBuilder sb = new StringBuilder(s);
if(s.charAt(0) == '-')
sb.deleteCharAt(0);
String n = sb.reverse().toString();
int N = 0 -Integer.parseInt(n);
if(N >= -2147483648 && N <= 2147483647)
return N;
return 0;
}
}
上述代码有什么问题。
答案 0 :(得分:0)
尝试:
public int reverse(int a) {
boolean negative = a < 0;
String s = Integer.toString(a);
StringBuilder sb = negative ? new StringBuilder(s.substring(1))
: new StringBuilder(s);
long reversed = Long.parseLong(sb.reverse().toString());
reversed = negative ? 0L - reversed : reversed;
if(reversed < MIN_VALUE || reversed > MAX_VALUE) {
return 0;
}
return Long.valueOf(reversed).intValue();
}