写了超级丑的代码,结果被 leetcode 的结果震惊了。
目前还没去看题解...不知道标准答案多简洁
1ms
击败 100.00%使用 Java 的用户
public int myAtoi(String s) {
int ng=1;
int cur=0;
int condition=0;
int i=0;
char chr = '\0';
while (i<s.length()) {
if(condition==0){ //start
chr=s.charAt(i++);
condition++;
}else if(condition==1){ //remove blank
while (chr==' ' && i<s.length()){
chr=s.charAt(i++);
}
condition++;
} else if(condition==2){ //check '-,+'
if(chr=='-'){
ng=-1;
chr=s.charAt(i++);
condition++;
continue;
}
if(chr=='+'){
chr=s.charAt(i++);
condition++;
continue;
}
if((chr>='0' && chr<='9')){
condition+=2;
continue;
}
return cur;
}else if(condition==3){ //remove '0'
while (chr=='0'){
chr=s.charAt(i++);
}
condition++;
}
else if(condition==4){
if(chr<'0'||chr>'9'){
return cur;
}
int value = (chr-'0')*ng;
if(cur>Integer.MAX_VALUE/10){
return Integer.MAX_VALUE;
} else if (cur<Integer.MIN_VALUE/10) {
return Integer.MIN_VALUE;
} else if (cur==Integer.MAX_VALUE/10) {
if (Integer.MAX_VALUE%10<value){
return Integer.MAX_VALUE;
}
}else if (cur==Integer.MIN_VALUE/10) {
if (Integer.MIN_VALUE%10>value){
return Integer.MIN_VALUE;
}
}
cur = cur*10+value;
chr=s.charAt(i++);
}
}
if(i==s.length()&&chr>='0'&&chr<='9'){
int value = (chr-'0')*ng;
if(cur>Integer.MAX_VALUE/10){
return Integer.MAX_VALUE;
} else if (cur<Integer.MIN_VALUE/10) {
return Integer.MIN_VALUE;
} else if (cur==Integer.MAX_VALUE/10) {
if (Integer.MAX_VALUE%10<value){
return Integer.MAX_VALUE;
}
}else if (cur==Integer.MIN_VALUE/10) {
if (Integer.MIN_VALUE%10>value){
return Integer.MIN_VALUE;
}
}
cur = cur*10+value;
}
return cur;
}
1
Goooooos 240 天前
这道题同样的代码,18 年的时候是 42ms ,刚才重新提交一次是 1ms
|