class Solution {
public int myAtoi(String str) {
/**
* ' ' +/- number other
* start start signed in_number end
* signed end end in_number end
* in_number end end in_number end
* end end end end end
*/
Map<String, String[]> map = new HashMap<>();
map.put("start", new String[]{"start", "signed", "in_number", "end"});
map.put("signed", new String[]{"end", "end", "in_number", "end"});
map.put("in_number", new String[]{"end", "end", "in_number", "end"});
map.put("end", new String[]{"end", "end", "end", "end"});
String status = "start";
int ans = 0;
int signed = 1;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
String[] ss = map.get(status);
status = ss[getIndex(c)];
//要轉(zhuǎn)為整型
int cc = c - 48;
if (status.equals("in_number")) {
// 注意,ans * 10 + cc>Integer.MAX_VALUE的變形
if (ans > (Integer.MAX_VALUE - cc) / 10) {
if (signed == 1) {
return Integer.MAX_VALUE;
} else {
return Integer.MIN_VALUE;
}
}
ans = ans * 10 + cc;
} else if (status.equals("signed")) {
signed = c == '+' ? 1 : -1;
}
}
return signed * ans;
}
public static int getIndex(char c) {
if (c == ' ') {
return 0;
} else if (c == '-' || c == '+') {
return 1;
} else if (Character.isDigit(c)) {
return 2;
} else {
return 3;
}
}
}