跟个智障一样,一道简单题调了俩点,可以说全程毫无难点,就是各种各样的各种情况考虑不全,这次记得下次必忘,还有就是换来换去还是那一种方法,也不知道在换什么,而且换半天,这个方法还没有进行到底。 蠢的一批。
题目描述
第n次解题
class Solution {
public int myAtoi(String s) {
String result= "";
int flag = 1;
int length = s.length();
char[] ch = s.toCharArray();
int i =0;
if(length <= 0){
return 0;
}
while(i<length && ch[i] == ' '){
i++;
}
if(i>=length)
return 0;
if(ch[i]!='-' &&ch[i]!='+'&& ch[i] < 48 || ch[i] >57)
return 0;
if(ch[i] == '-'){
flag = -1;
i++;
} else if(ch[i] == '+'){
flag = 1;
i++;
}
while(i<length && (ch[i]>=48 && ch[i] <=57)){
result += ch[i];
i++;
}
if(result.length()<=0){
return 0;
// System.out.println("false");
}
int temp;
try {
temp = Integer.parseInt(result) * flag;
return temp;
//System.out.print(temp);
} catch (NumberFormatException e) {
// e.printStackTrace();
if(flag > 0)
temp = 2147483647;
else
temp = -2147483648;
return temp;
// System.out.print(temp);
}
}
}
题解-自动机
class Solution {
public int myAtoi(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;
}
}