
写了超级丑的代码,结果被 eetcode 的结果震惊了。 目前还没去看题解...不知道标准答案多简洁
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 uNoBrain 2024-04-16 15:10:15 +08:00 这道题同样的代码,18 年的时候是 42ms ,刚才重新提交一次是 1ms |