Share my c++ sulotion


  • 0
    Z
    bool isValid(char a)
    {
        if(a>='0'&&a<='9')
        {
            return true;
        }
        return false;
    }
    int myAtoi(string str) {
    	int len = str.length();
    	int begin = 0;
    	for (int i = 0; i<len; i++)
    	{
    		if (str[i] == ' ')
    		{
    			begin = i+1;
    		}
    		else
    		{
    			break;
    		}
    	}
    	if (begin >= len)
    		return 0;
    	str = str.substr(begin, str.size());
    	cout << str.c_str() << endl;
    	len = str.length();
    	int res = 0;
    	bool isBegin = 0;
    	int tmp;
    	bool post = 1;
    
    	for (int i = 0; i<len; i++)
    	{
    		if (i == 0 && str[i] == '+')
    			continue;
    		if (i == 0 && str[i] == '-')
    		{
    			post = 0;
    			continue;
    		}
    		if (isValid(str[i]))
    		{
    			isBegin = 1;
    			tmp = res * 10 + str[i] - '0';
    			if (tmp / 10 != res)
    			{
    				if(!post)
    				    return INT_MIN;
    				return INT_MAX ;
    			}
    			res = tmp;
    		}
    		else if (isBegin)
    		{
    			break;
    		}
    		else
    		{
    			return 0;
    		}
    	}
    	if (!post)
    	{
    		res = -res;
    	}
    	return res;
    }

Log in to reply
 

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