这题算法不是特别困难,主要是在判断数字数字越界的地方卡了很久。
在每次数字拼接前,判断当前所求的数字是否大于最大值的 1 / 10,
int bndry = Integer.MAX_VALUE / 10;
然后存在以下两种情况可能造成越界。
-
result > bndry
执行拼接10×result ≥ 2147483647越界 -
result = bndry , x > 7
执行拼接后是2147483648或者2147483649造成越界然后是本题ac代码
class Solution {
public int strToInt(String str) {
str = str.trim();
int result = 0;
int cheng = 1;
boolean flag = false;
int bndry = Integer.MAX_VALUE / 10;
for (int i=0; i<str.length();i++){
if (i == 0 && str.charAt(i) == '-' ){
flag = true;
}else if (i == 0 && str.charAt(i) == '+' ){
flag = false;
}else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
if (result > bndry || (result == bndry && str.charAt(i) > '7')) {
return flag == true ? Integer.MIN_VALUE : Integer.MAX_VALUE;
// 数字越界处理
}
int i1 = Integer.parseInt(String.valueOf(str.charAt(i)));
result = result * 10 + i1;
} else {
break;
}
}
if (flag)
result = -1 * result;
return result;
}
}