美文网首页
8. String to Integer (atoi)

8. String to Integer (atoi)

作者: 一棵会开花的树_f654 | 来源:发表于2018-01-19 16:33 被阅读0次

第二题就挑了个难的。。。。
题目描述如下:
Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
一开始以为很简单,后来逐渐发现还是有很多需要注意的地方:
1.空字符串
2.带正负号的,如"-567","+234"
3.以有效数字开头,但之后有非有效字符的,如"-672---","98jdk"
4.以空字符开头的,之后的非空字符是有效数字的,如" 010"
5.一山比一山高啊,以为第4种情况就是极限了,没想到还有这种," +0 123"

再写一下由于自己的失误造成的问题:
一、前三种情况通过,第四种情况错误

class Solution {
    public int myAtoi(String str) {
        if(str.length() == 0) return 0;
        int len = str.length();
        int number=0;
        char[] c = new char[len];
        boolean flag = true;
        int tag = 0;
        for(int i=0; i<len; i++){
            char num = str.charAt(i);
            if(num<'0' || num>'9'){
                if((num=='+' || num=='-') && flag==true) flag=false;
                else if(num == ' ')  continue;
                else 
                    break;
            }
            c[i] = str.charAt(i);
            tag++;
        }
        if(c.length==1&&(c[0]==43||c[0]==45)) return 0;
        switch(c[0]){
            case '+':
                for(int i=1; i<tag; i++){
                    number += (c[i]-48) * Math.pow(10, tag-1-i); 
                }
                break;
            case '-':
                for(int i=1; i<tag; i++) number -= (c[i]-48) * Math.pow(10, tag-1-i); 
                break;
            default:
                for(int i=0;i<tag; i++) number += (c[i]-48) * Math.pow(10, tag-1-i); 
                break;
        }
           
        return number;   
    }
}
image.png

后来分别输出了tag和c[5],发现是对的(3,1),然后突然发现现在的c是这样的

[' ',' ',' ','0','1','0']

按之前的处理方式取前tag位就不对了,解决方法如下(只贴了有改动的部分):

if(num<'0' || num>'9'){
  if((num=='+' || num=='-') && flag==true) {
    flag=false;
    c[tag++] = str.charAt(i);
  }
  else if(num == ' ' ) continue;
  else break;
 }else{
  c[tag++] = str.charAt(i);
 }

二、本来以为万事大吉了,结果又出了一种情况,即情况5


image.png

应该还是自己在处理空字符的时候没有考虑到这种情况,一味地continue,其实应该只有在出现非空字符之前这样处理,之后就要按其他非数字字符处理,修改后的代码:

else if(num == ' ' && tag == 0) continue;

啊啊啊啊啊啊啊,解决了第五种情况就顺利通过了,但是性能上的表现不太好,第一遍就先这样吧,太恶心了这道题!!!

相关文章

网友评论

      本文标题:8. String to Integer (atoi)

      本文链接:https://www.haomeiwen.com/subject/yqxaoxtx.html