把字符串转化为整数(循环判断注意边界条件)

把字符串转换成整数

http://www.nowcoder.com/questionTerminal/1277c681251b4372bdef344468e4f26e

class Solution {
public:
    int StrToInt(string str) {
        const int len = str.length(); //字符串长度
        if (len == 0) return 0;
        int i = 0;
        while (i < len && str[i] == ' ') { ++i; } // 排除开头的空格
        if (i == len) return 0;
        if (!isdigit(str[i]) && str[i] != '+' && str[i] != '-') return 0; // 判断是否是数字isdigit
        bool neg = str[i]=='-' ? true : false;
        i = isdigit(str[i]) ? i : i+1;
        long long ans = 0L;

        while (i < len && isdigit(str[i])) {
            ans = ans * 10 + (str[i++]-'0');

            if (!neg && ans > INT_MAX) { // 如果该函数为正值,最大为最大值
                ans = INT_MAX;
                break;
            }
            if (neg && ans > 1L + INT_MAX) { // 为负值可以为 最大值+1
                ans = 1L + INT_MAX;
                break;
            }
        }
        if (i != len) return 0; // 不要此处,就是atoi()库函数的实现
        return !neg ? static_cast<int>(ans) : static_cast<int>(-ans);
    }
};

全部评论

相关推荐

92Y:泡成巨人观了吧
投递百度等公司10个岗位
点赞 评论 收藏
分享
想玩飞盘的菠萝蜜在春...:上交✌🏻也拒?
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务