c++ solution


  • 0
    P

    class Solution {
    public:
    std::string trimSpace(const std::string& str)
    {
    bool is_first = true, is_end = false;
    size_t start = 0, end = str.size();
    for(size_t i = 0; i < str.size(); ++ i)
    {
    if(str[i] == ' ')
    {
    start ++;
    }
    else
    {
    break;
    }
    }

        if(start == str.size())
        {
            return "";
        }
        
        for(size_t i = str.size() - 1; i >= 0; -- i)
        {
            if(str[i] == ' ')
            {
                end --;
            }
            else
            {
                break;
            }
        }
        
        return str.substr(start, end - start);
    }
    
    int myAtoi(string str) {
        str = trimSpace(str);
        
        if(str.empty()) return 0;
        
        bool is_negative = false;
        size_t index = 0;
        if(str[0] == '-') 
        {
            is_negative = true;
            index = 1;
        }
        else if(str[0] == '+')
        {
            index = 1;
        }
        
        int64_t result = 0;
        for(size_t i = index; i < str.length(); ++ i)
        {
            if((str[i] >= '0') && (str[i] <= '9'))
            {
                result = result * 10 + str[i] - '0';
                if(result >= 2147483648)
                {
                    result = 2147483648;
                    break;
                }
            }
            else
            {
                break;
            }
        }
        
        if(is_negative) 
        {
            result = -result;    
        }
        else
        {
            if(result > 2147483647)
            {
                result = 2147483647;
            }
        }
        
        return (int)result;
    }
    

    };


Log in to reply
 

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