字符串转整数(atoi)

#include <iostream>
#include <string>
using namespace std;

class Solution
{
public:
    int myAtoi(string str)
    {
        /*在此补全代码*/
        int pos = -1;
        long long  ans = 0;
        int zhengfu = 1;
        int fuhaobianhuan = 0, begin = 0;
        for (int i = 0; i < str.length(); i++)
        {
            if (str[i] >= '0'&&str[i] <= '9')
            {
                if (str[i] == '0'&&begin == 0)
                {
                    pos = i;
                    continue;
                }
                begin++;
                if (begin > 10)
                {
                    if (zhengfu == -1)
                    {
                        return INT_MIN;
                    }
                    return INT_MAX;
                }
                int te = str[i] - 48;
                ans *= 10;
                ans += te;
                if ((i-pos!=begin)&&pos!=-1)
                {
                    return 0;
                }
            }
            else if (str[i] == ' ')
            {
                if (fuhaobianhuan!=0||pos!=-1||begin!=0)
                {
                    break;
                }
                continue;
            }
            else if (str[i] == '-')
            {
                if (pos==-1&&begin!=0)
                {
                    break;
                }
                fuhaobianhuan++;
                zhengfu = -1;
            }
            else if (str[i] == '+')
            {
                if ( pos != -1&&begin==0)
                {
                    return 0;
                }
                if (pos == -1 && begin != 0)
                {
                    break;
                }
                fuhaobianhuan++;
            }
            else
            {
                break;
            }

        }
        string s = to_string(ans);

        if (fuhaobianhuan < 2 && s.length() == begin)
        {
            if (ans > INT_MAX || ans < INT_MIN)
            {
                if (zhengfu == -1)
                {
                    return INT_MIN;
                }
                return INT_MAX;
            }
            return zhengfu * ans;
            return zhengfu * ans;
        }
        return 0;
    }
};

int main()

{
    Solution s;
    string str;
    getline(cin, str);
    cout << s.myAtoi(str);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/kongqingxin12/article/details/82143177