【解题思路】
能挣扎一下,但不多(大哭……)
class Solution {
public int strToInt(String str) {
StringBuffer buffer = new StringBuffer(str);
int len = buffer.length();
boolean fuHao = true;
StringBuffer zheng = new StringBuffer();
int ans = 0;
while(buffer.charAt(0) == ' ')
{
buffer.deleteCharAt(0);
}
if(isFuHao(buffer.charAt(0)) == 2)
{
fuHao = false;
buffer.delete(0,1);
}
else if(isFuHao(buffer.charAt(0)) == 1)
{
buffer.delete(0,1);
}
else if(!isShu(buffer.charAt(0)))
{
return 0;
}
while(buffer.length() > 0)
{
if(isShu(buffer.charAt(0)))
{
zheng.append(buffer.charAt(0));
}
buffer.delete(0,1);
}
int tmp = charToInt(zheng.charAt(0));
for(int i = 1; i < zheng.length(); i++)
{
ans = tmp*10 + charToInt(zheng.charAt(i));
tmp = ans;
}
if(!fuHao) return(0-ans);
return ans;
}
public int isFuHao(char c)
{
if(c == '+') return 1;
else if(c == '-') return 2;
else return 0;
}
public boolean isShu(char c)
{
if(c=='0' || c=='1' || c=='2' || c=='3' || c=='4' || c=='5' || c=='6' ||c=='7' || c=='8' || c=='9')
{
return true;
}
return false;
}
public int charToInt(char c)
{
if(c=='0') return 0;
else if(c=='1') return 1;
else if(c=='2') return 2;
else if(c=='3') return 3;
else if(c=='4') return 4;
else if(c=='5') return 5;
else if(c=='6') return 6;
else if(c=='7') return 7;
else if(c=='8') return 8;
else if(c=='9') return 9;
return 10;
}
}
class Solution {
public int strToInt(String str) {
Automaton automaton = new Automaton();
int length = str.length();
for (int i = 0; i < length; ++i) {
automaton.get(str.charAt(i));
}
return (int) (automaton.sign * automaton.ans);
}
}
class Automaton {
public int sign = 1;
public long ans = 0;
private String state = "start";
private Map<String, String[]> table = new HashMap<String, String[]>() {{
put("start", new String[]{"start", "signed", "in_number", "end"});
put("signed", new String[]{"end", "end", "in_number", "end"});
put("in_number", new String[]{"end", "end", "in_number", "end"});
put("end", new String[]{"end", "end", "end", "end"});
}};
public void get(char c) {
state = table.get(state)[get_col(c)];
if ("in_number".equals(state)) {
ans = ans * 10 + c - '0';
ans = sign == 1 ? Math.min(ans, (long) Integer.MAX_VALUE) : Math.min(ans, -(long) Integer.MIN_VALUE);
} else if ("signed".equals(state)) {
sign = c == '+' ? 1 : -1;
}
}
private int get_col(char c) {
if (c == ' ') {
return 0;
}
if (c == '+' || c == '-') {
return 1;
}
if (Character.isDigit(c)) {
return 2;
}
return 3;
}
}