美文网首页
字符串转换成数字

字符串转换成数字

作者: cde99bf0b5b1 | 来源:发表于2017-09-29 22:20 被阅读0次
    class Solution {
    public:
        int myAtoi(string str) {
            long num = 0;
            int sign = 1;
            //int i = str.find_first_not_of(' ');
            //sign = (str[i++] == '-') ? -1 : 1;
            int i = 0;
            i = str.find_first_not_of(' ');
            if(str[i] == '+' || str[i] == '-')
                sign = (str[i++] == '-') ? -1:1;
            if(str[i] < '0' || str[i] > '9')
                return 0;
            while(str[i] >= '0' && str[i] <= '9' && i < str.size()){
                    num = num*10 + (str[i++] - '0');
                    if(sign*num > INT_MAX) return INT_MAX;
                    if(sign*num < INT_MIN) return INT_MIN;
            }  
            return sign*num;
        }
    };
    

    相关文章

      网友评论

          本文标题:字符串转换成数字

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