Easy to understand 12ms C++ code


  • 0
    Q
    class Solution {
    public:
        int myAtoi(string str) {
            long long sum = 0;
            bool negative = false; //to check if the its negative
            bool rep = false;      //to check if there are multiple alphabet in the front
            bool isMiddle = false; //to check if there are whitespace in the middle of string
            char t;
            for(int i = 0; i < str.length(); ++i){
                t = str.at(i);
                if(t < 48 || t > 57){        //check if str[i] is a number
                    if(t == 43 || t == 45){  //check if str[i] is a sign 
                        if(rep == true)
                            return 0;
                        rep = true;
                        if(t == 45)
                            negative = true;
                        continue;
                    }
                    else if(t == 32){
                        if(rep == true)
                            return 0;
                        if(isMiddle)
                            break;
                        continue;
                    }
                    else
                        break;
                }
                isMiddle = true;
                sum = sum * 10 + (t - '0'); //convert str to int
                
                //int bound check
                if(sum > INT_MAX && !negative)
                    return INT_MAX;
                if(sum > INT_MAX && negative)
                    return INT_MIN;
            }
            if(negative){
                sum = 0 - sum;
            }
            return sum;
        }
    };`

Log in to reply
 

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