Share 8ms C++ solution


  • 0
    T
    class Solution {
    public:
        int myAtoi(string str) {
            int n = str.length();
            char ss[n+1];
            strcpy(ss, str.c_str());
            int i;
            int sign = 1;
            for(i=0; i<n; i++)
                if(ss[i] != ' ')
                    break;
                    
            if(ss[i] == '+')
                i = i+1;
            else if(ss[i] == '-')
            {
                i=i+1;
                sign = -1;
            }
            
            int j;
            long long int value=0;
            for(j=i; j<n; j++)
            {
                if(ss[j] < '0' || ss[j] > '9')
                    break;
                value = 10*value + (ss[j]-'0');
                if(value > INT_MAX)
                {
                    if(sign == 1)
                        return INT_MAX;
                    else
                        return INT_MIN;
                }
            }
            value = value*sign;
            
            int result=0;
            result = (int) value;
                
            return result;
        }
    };

Log in to reply
 

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