/*
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1924)
at Solution.myAtoi(Solution.java:26)
at __DriverSolution__.__helper__(__Driver__.java:4)
at __Driver__.main(__Driver__.java:48)
Last executed input:" -42"
如果str是空 return 0;
findfirstnonwhite; return 位置或者-1;//函数中判断第一个是不是数字 不是数字或者‘-’ return -1;
findlastdigit; return 位置;
去除sub 判断是否越界;越界返回最大值;判断方法是 设置一个long类型的变量 ;
*/
class Solution {
public int myAtoi(String str) {
if(str == null || str.length() == 0) {
return 0;
}
int firstPos = findFirstNonWhite(str);
if(firstPos == -1) {
return 0;
}
int lastPos = findLastDigit(str,firstPos);
int sign = 1;
String subStr;
if(str.charAt(firstPos) == '-'){
sign = -1;
subStr = str.substring(firstPos + 1, lastPos);
}else {
subStr = str.substring(firstPos, lastPos);
}
long num = 0L;
for(char c : subStr.toCharArray()) {
num = num * 10 + (c - '0');
}
num = num * sign;
if(num > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if(num < Integer.MIN_VALUE) return Integer.MIN_VALUE;
return (int)num;
}
public int findFirstNonWhite(String s) {
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' '){
continue;
}else if(s.charAt(i) == '-' || ('0' <= s.charAt(i) && s.charAt(i) <= '9') || s.charAt(i) == '+') {
return i;
}else {
return -1;
}
}
return -1;
}
public int findLastDigit(String s, int start) {
while(start < s.length() &&'0' <= s.charAt(start) && s.charAt(start) <= '9') {
start++;
}
return start;
}
}