class Solution {
static final int MAXDIV10 = Integer.MAX_VALUE / 10;
public int myAtoi(String s) {
int res = 0;
if(Objects.isNull(s) || s.length() == 0) return 0;
int len = s.length(), index = 0, sign = 1;
while(index < len && s.charAt(index) == ' ') ++index;
if(index < len && s.charAt(index) == '+'){
++index;
}else if(index < len && s.charAt(index) == '-') {
sign = -1;
++index;
}
while(index < len && Character.isDigit(s.charAt(index))) {
int val = s.charAt(index) - '0';
//-2147483648
//2147483647
if(res > MAXDIV10 || (res == MAXDIV10 && val >= 8)) {
//2147483647 即res == MAXDIV10&& val=7 没有进来
return (sign == 1)?Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + val;
++index;
}
while(index < len && s.charAt(index) == ' ') ++index;
return sign * res;
}
}
8.String to Integer (atoi)
于 2018-08-15 01:26:36 首次发布