My C++ Solution 9ms


  • 0

    If you have one idea to improve this code, please feel free to contact with me.

    alt text

    class Solution
    {
    	public:
    	int myAtoi(string str)
    	{
    		long long res = 0;
    
    		if(0 == str.size())
    		{
    			return res;
    		}
    
    		auto i = str.begin();
    
    		while(i != str.end() && isspace(*i))
    		{
    			++i;
    		}
    		if(i == str.end())
    		{
    			return res;
    		}
    
    		bool flag = true;
    
    		int sign = 1;
    
    		for(; i != str.end(); ++i)
    		{
    			if(flag&&*i == '-')
    			{
    				sign = -1;
    				flag = false;
    				continue;
    			}
    			else if(flag&&*i == '+')
    			{
    				flag = false;
    				continue;
    			}
    
    			if(*i >= '0'&&*i <= '9')
    			{
    				res = res * 10 + (*i - '0');
    			}
    			else
    			{
    				break;
    			}
    			if(res > INT_MAX)
    			{
    				break;
    			}
    		}
    		res = sign*res;
    		
    		if(res > INT_MAX)
    		{
    			res = INT_MAX;
    		}
    		else if(res < INT_MIN)
    		{
    			res = INT_MIN;
    		}
    		
    		return static_cast<int>(res);
    	}
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.