把字符串转换成整数

class Solution {
public:
    bool check(char c)
    {
        if(c=='+')  return true;
        if(c=='-')  return true;
        if(c>='0'&&c<='9')  return true;
        return false;
    }
    int strToInt(string str) {
        long long res=0;
        int i=0;
        bool flag=false;
        while(str[i]==' ')   i++;
        if(!check(str[i]))   return 0;
        if(str[i]=='-'||str[i]=='+')
        {
            if(str[i]=='-') flag=true;
            i++;
        }
        while(i < str.size()&&check(str[i]))
        {
            res=res*10+(str[i]-'0');
            if(res>INT_MAX)
            {
                if(flag)    return INT_MIN;
                else return INT_MAX;
            }
            i++;
        }
        if(flag)    res=-res;
        return res;
    }
};
posted @ 2023-05-18 20:57  穿过雾的阴霾  阅读(19)  评论(0)    收藏  举报