cpp solution with preprocess and overflow consideration


  • 0
    R
    #include <iostream>
    #include <limits.h>
    #include <ctype.h>
    
    class Solution
    {
      public:
        int myAtoi(std::string s)
        {
    
            // trim prefix empty str
            while (s.length() >= 1 && s[0] == ' ')
            {
                s = s.substr(1);
            }
            // std::cout<<s<<std::endl;
            // sign
            int sign = 1;
            if (s[0] == '-')
            {
                sign = -1;
                s = s.substr(1);
            }
            else if (s[0] == '+')
            {
                sign = 1;
                s = s.substr(1);
            }
            // std::cout<<s<<std::endl;
            //trim suffix
            int len = s.length(),i ;
            for (i = 0; i < len; ++i)
            {
                if (!isdigit(s[i]))
                {
                    s = s.substr(0, i);
                    break;
                }
            }
            // std::cout<<s<<","<<sign<<std::endl;
            long long result = 0;
    
            if (s.length() > 10)
            {
                if (sign == 1)
                {
                    return INT_MAX;
                }
                else
                {
                    return INT_MIN;
                }
            }
    
            // std::cout<<"str:"<<s<<std::endl;
            i = 0;
            len = s.length();
            while (i < len && isdigit(s[i]))
            {
                result = result * 10 + (s[i] - '0');
                ++i;
            }
            result *= sign;
            // std::cout<<"result:"<<result<<std::endl;
            if (result > INT_MAX)
            {
                return INT_MAX;
            }
            else if (result < INT_MIN)
            {
                return INT_MIN;
            }
            else
            {
                return result;
            }
        }
    };
    
    int main(int argc, char const *argv[])
    {
        Solution s;
        std::string str = "-91283472332";
        str = "words and 987";
        str = "4193 with words";
        str = "   -42";
        str = "   +1";
        str = "9223372036854775809";
        str = "4193 with words";
        str = "-91283472332";
        std::cout << s.myAtoi(str);
        return 0;
    }
    
    

Log in to reply
 

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