难点:
假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 。
所以不能使用long类型存储数据。
越界的处理逻辑:
因为 ,设 ,若 res > bndry || res == bndry && ch[i] > '7'
,则说明越界了。
class Solution {
public int strToInt(String str) {
int res = 0, bndry = Integer.MAX_VALUE / 10;
int i = 0, sign = 1, n = str.length();
char[] ch = str.toCharArray();
while(i < n && ch[i] == ' ') i++; // 处理前导空格
if(i == n) return 0;
if(ch[i] == '-') sign = -1; // 处理符号
if(ch[i] == '-' || ch[i] == '+') i++;
while(i < n){
if(ch[i] < '0' || ch[i] > '9') break;
if(res > bndry || res == bndry && ch[i] > '7'){
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + (ch[i] - '0');
i++;
}
return res * sign;
}
}