Leetcode 8. 字符串转换整数 (atoi)(DAY 165)---- LeetCode 精选 TOP 面试题

文章目录


原题题目


Leetcode 8. 字符串转换整数 (atoi)(DAY 165)---- LeetCode 精选 TOP 面试题


代码实现(首刷自解)


class Solution {
public:
    int myAtoi(string s) {
        bool neg = false,wrong = false,numend = false,dealnum = false;;
        long ret = 0;
        int numdeal = -1;
        for(int i=0;i<s.size();++i)
        {
            char chr = s[i];
            if(chr != ' ' && chr != '-' && chr != '+'  && (chr > '9' || chr < '0'))
            {
                wrong = true;
                break;
            }
            if(chr == ' ')  continue;
            else if(chr == '-' || chr == '+' || (chr >= '0' && chr <= '9'))
            {
                if(chr == '-')  neg = true;
                numdeal = i;
                if(chr == '-' || chr == '+')    ++numdeal;
                break;
            }       
        }
        
        if(numdeal == -1)   wrong = true;
        for(int i=numdeal;!wrong && i<s.size();++i)
        {
            char chr = s[i];
            if(chr < '0' || chr > '9')    
            {
                if(numend) wrong = true;
                else numend = true;
                break;
            }
            else
            {
                ret *= 10;
                ret += (chr - '0');
                if(ret > INT_MAX)
                {
                    if(neg) ret = INT_MIN;
                    else    ret = INT_MAX;
                    dealnum = true;
                    break;
                }
            }
        }

        if(!dealnum) ret = (neg) ? -ret : ret; 
        if(wrong)   ret = 0;
        return (int)ret;
    }
};
上一篇:数据结构-图(邻接矩阵实现)


下一篇:数组中赋值的问题