A 12ms C++ Solution, maybe a little long comparing to other solution


  • 0
    Y
    class Solution {
    public:
        int myAtoi(string str) {
            vector<int> num;
            long res = 0;
            bool sign = true, signFound = false;
            for(int i = 0; i < str.length(); i++) {
                if((str[i] == ' ')&&(signFound == false)) continue;
                if((str[i] == ' ')&&(signFound == true)) break;
                
                if((str[i] == '+')&&signFound == false) {
                    signFound = true;
                    continue;
                }
                if((str[i] == '+')&&signFound == true) return 0;
                
                if((str[i] == '-')&&signFound == false) {
                    sign = false;
                    signFound = true;
                    continue;
                }
                if((str[i] == '-')&&signFound == true) return 0;
                if(((str[i] - '0') >= 0)&&((str[i] - '9') <= 0)) {
                    num.push_back(str[i] - '0');
                    signFound = true;
                } else break;
            }
            for(int j = num.size() - 1; j >= 0; j--) {
                res += num[j]*pow(10,num.size() - 1 - j);
                if(sign) if(res >= INT_MAX) return INT_MAX;
                if(!sign) if(-res <= INT_MIN) return INT_MIN;
                
            }
            if(sign) return res;
                return -res;
        }
    };

Log in to reply
 

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