题解 | #把字符串转换成整数#

把字符串转换成整数

https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e

class Solution {
public:
    static int StrToInt(string str) {
        int i = 0;
        vector<char> ch;
        set<char> charset = {'1','2','3','4','5','6','7','8','9'};
        /*if (!(str[0] >= 48 || str[0] <= 57)||str[0]!='-'||str[0]!='+')
        {
            return 0;
        }*/
       if(str=="")
       {
       return 0;
       }
        while (i < str.length())
        {
            if ( str[0] == '-' || str[0] == '+' || ( charset.end()!= charset.find(str[i])))
            {
                ch.push_back(str[i]);
            }
            else
            {
                break;
            }

            ++i;
        }
        if (i < str.length())
        {
            return 0;
        }


        int ret = 0;
        int temp = 0;
        if (ch[0] == '+')
        {
            int i = 1;
            while (i < ch.size())
            {
                temp = ch[i] - '0';
                ret = ret * 10 + temp;
                i++;
            }

        }
        else if (ch[0] == '-')
        {
            int i = 1;
            while (i < ch.size())
            {
                temp = ch[i] - '0';
                ret = ret * 10 + temp;
                i++;
            }
            ret = -ret;
        }
        else
        {
            int i = 0;
            while (i < ch.size())
            {
                temp = ch[i] - '0';
                ret = ret * 10 + temp;
                i++;
            }
        }
        return ret;
    }
};

#晒一晒我的offer##我的实习求职记录#
全部评论

相关推荐

10-25 00:32
香梨想要offer:感觉考研以后好好学 后面能乱杀,目前这简历有点难
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务