C++ Solution O(n)


  • 0
    E
    int myAtoi(string str) {
        bool start = false;
        int sign = 1;
        int num = 0;
        int loc = 0;
        while(loc < str.size()) {
            if(str[loc]==' ' && !start){
                loc++;
            }
            else if(str[loc]=='+' && !start){
                loc++;
                start = true;
            }
            else if(str[loc]=='-' && !start){
                loc++;
                sign = -1;
                start = true;
            }
            else if(!isdigit(str[loc])){
                break;
            }
            else {
    			start = true;
    			num = num *10 + (str[loc] - 48);
                            loc++;
    			if(num % 10 != (str[loc] - 48)){
    				if(sign == 1)    return INT_MAX;
    				else    return INT_MIN;
    			}
    		}
        }
        return num * sign;
    }

Log in to reply
 

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