One pass solution without using method of string


  • 0
    F
    int myAtoi(string str){
    
        if (str.empty())
            return 0;
    
        int IMIN = std::numeric_limits<int>::min();
        int IMAX = std::numeric_limits<int>::max();
        long sign = 1, num = 0;
        bool num_start = false;
    
        for (const char & c: str){
            if (!num_start){
                if (isspace(c))
                    continue;
                else{
                    num_start = true;
                    if (c == '+')
                        sign = 1;
                    else if (c == '-')
                        sign = -1;
                    else if (isdigit(c)){
                        num = num * 10 + c - '0';
                    }
                    else
                        break;
                }
            }
            else{
                if (isdigit(c)){
                     num = num * 10 + c - '0';
                    if (num * sign > IMAX) return IMAX;
                    if (num * sign < IMIN) return IMIN;
                   
                }
                else
                    break;
            }
        }
    
        return num * sign;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.