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

8. String to Integer (atoi)

作者: 凉拌姨妈好吃 | 来源:发表于2018-06-04 20:25 被阅读0次

    实现atoi函数,注意越界问题


    image.png

    思路:一定要注意考虑越界问题,如果保存的数据超过int的最大值或最小值,就返回INT_MAX或INT_MIN。用long来保持数据,就可以判断数据有没有超过int的最大或最小值

    class Solution {
    public:
        int myAtoi(string str) {
            
            bool negative = false; 
            long num = 0;  
            if(str.size()<=0)
                return 0;
            
            for(int i = 0;i<str.size();)
            {
                while(str[i]==' ')
                i++;
    
                if(str[i]>'9'||str[i]<'0')
                {
                    if(str[i]=='-'||str[i]=='+')
                    {                     
                        negative = (str[i]=='-')?true:false;
                        i++;
                    }
                }
                while('0'<=str[i]&&str[i]<='9')
                {
                    num = num*10+(str[i]-'0');
                    i++;
                    
                    if(negative&&((-num)<=INT_MIN)) return INT_MIN;
                    if((!negative)&&((num)>=INT_MAX)) return INT_MAX;
                }
                return (negative ==true)?-num:num; 
            }
           
        }
    };
    

    别人的优化,用-1和1,感觉更简单一点

    int myAtoi(string str) {
        long result = 0;
        int indicator = 1;
        for(int i = 0; i<str.size();)
        {
            i = str.find_first_not_of(' ');
            if(str[i] == '-' || str[i] == '+')
                indicator = (str[i++] == '-')? -1 : 1;
            while('0'<= str[i] && str[i] <= '9') 
            {
                result = result*10 + (str[i++]-'0');
                if(result*indicator >= INT_MAX) return INT_MAX;
                if(result*indicator <= INT_MIN) return INT_MIN;                
            }
            return result*indicator;
        }
    }
    

    相关文章

      网友评论

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

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