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

把字符串转换成整数

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

class Solution {
public:
    int StrToInt(string str) {
        if (str == "") return 0;
        long long res = 0;
        bool up = true;
        int i = 0;
        if (str[i] == '+' || str[i] == '-') {
            if (str[i] == '-') up = false;
            i++;
        }
        for (; i < str.length(); i++) {
            if (str[i] >= '0' && str[i] <= '9') {
                res = res * 10 + str[i] - '0';
                if (up && res >= INT_MAX) return INT_MAX;
                if (!up && (-res <= INT_MIN)) return INT_MIN;
            }
            else return 0;
        }
        return up? res: -res;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务