[数学] leetcode 8 String to Integer (atoi)

problem:https://leetcode.com/problems/string-to-integer-atoi/

        This very question before the question number, but has not done. Today, just over five times to mention, this question finally know why the pass rate so low. Mainly if / else Exercise, especially after totally did not see the question hang in many places.

class Solution {
public:
    int myAtoi(string str) {
        unsigned long long res = 0;
        bool bPositive = true;
        bool bFind = false;
        for(int i = 0;i < str.size();i++)
        {
            if(str[i] == ' ') 
            {
                if(bFind) return bPositive ? res : -res;
                else continue;
            }
            if(!bFind && str[i] == '-')
            {
                bFind = true;
                bPositive = false;
                continue;
            }
            if(!bFind && str[i] == '+')
            {
                bFind = true;
                bPositive = true;
                continue;
            }           
            if(!isdigit(str[i])) return bPositive ? res : -res;
            bFind = true;
            unsigned long long num = str[i] - '0';
            res = 10 * res + num;
            if(res >= INT_MAX) 
            {
                if(!bPositive)
                {
                    if(res == INT_MAX) return -INT_MAX;
                    else return INT_MIN;
                }
                return INT_MAX;
            }
        }
        return bPositive ? res : -res;
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11291718.html