美文网首页
8. String to Integer (atoi)字符串转整

8. String to Integer (atoi)字符串转整

作者: 羲牧 | 来源:发表于2020-07-22 22:23 被阅读0次

整型限定在INT_MIN: -2147483648和INT_MAX: 2147483647之间,若出现溢出的情况,则输出上述值。

class Solution {
public:
    int myAtoi(string str) {
        int num = 0;
        int sign = 1;
        const int len = str.size();
        int i = 0;
        while(str[i] == ' ' && i < len) i++;
        //只允许在开头出现一个+或-,若后续再出现非0-9之外的字符,直接跳过
        if(str[i] == '+' || str[i] == '-'){
            if(str[i] == '-') {
                sign = -1;
            }
            i++;
        } 
        for(;i < len; i++){
            if(str[i] < '0' || str[i] > '9') break;
            //若还有新字符,则当前num值不能大于INT_MAX/10;或者num=INT_MAX/10但是即将增加的字符大于限定值
            //为什么只需要判断与INT_MAX呢?差异只在于-2147483648,而刚好会提前退出,返回INT_MIN
            if(num > INT_MAX/10 ||
              (num == INT_MAX/10 && (str[i]-'0') > INT_MAX%10)){
                return sign == -1 ? INT_MIN:INT_MAX;
            }
            num = num*10 + (str[i]-'0');
        }
        return num*sign;
    }
};

相关文章

网友评论

      本文标题:8. String to Integer (atoi)字符串转整

      本文链接:https://www.haomeiwen.com/subject/djkxlktx.html