把字符串转换成整数

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 @   穿过雾的阴霾  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示