这道题题目好理解,主要难点就是在处理越界的情况
class Solution {
public int strToInt(String str) {
//首先将字符串转化为字符数组,并且去除掉首尾多余的空格
char[] c = str.trim().toCharArray();
if(c.length == 0) return 0;
//bnary最后是用来判断是否越界的标准
int res = 0, bndry = Integer.MAX_VALUE / 10;
int i = 1, sign = 1;
//判断是正整数还是负整数
if(c[0] == '-') sign = -1;
else if(c[0] != '+') i = 0;
for(int j = i; j < c.length; j++) {
//一旦碰到字符就直接退出,遍历结束
if(c[j] < '0' || c[j] > '9') break;
if(res > bndry || res == bndry && c[j] > '7') return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
//没越界的情况下就是进行计数
res = res * 10 + (c[j] - '0');
}
return sign * res;
}
}
这里我主要来说明越界部分的判断
if(res > bndry || res == bndry && c[j] > '7')
return sign == 1 ? Integer.MAX_VALUE :
Integer.MIN_VALUE;
Integer.Max_Value=2147483647
bnary=Integer.Max_Value/10=214748364
①当目前的res>bnary的时候,如果指定后面的10,肯定会越界
②当res=bnary的时候,说明10是不会越界,但是后面还需要加上c[j]-‘0’,所以如果c[j]-'0’小于等于7的话,res就不会越界,如果c[j]-'0’大于7的话,最后执行加的时候就会越界。如果越界的话,判断这个数是正数还是负数,如果是正数就是返回Integer.Max_Value.如果是负数返回Integer.Min_Value