Atoi is much much faster than stoi 85 ms to 15ms when changed to atoi


  • 0
    P
    //solution 1: using stoi / runtime 85ms
    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
            stack<int> s;
            for (int i = 0; i < tokens.size(); ++i) {
                try {
                    int num = stoi(tokens[i], NULL, 10);
                    s.push(num);
                } catch (const std::invalid_argument& ia) {
                    int op2 = s.top();
                    s.pop();
                    int op1 = s.top();
                    s.pop();
                    int res = getResult(op1, op2, tokens[i][0]);
                    s.push(res);
                }
            }
            return s.top();
        }
        
        inline int getResult(int op1, int op2, char op) {
            switch(op) {
                case '+' : return op1 + op2;
                case '-' : return op1-op2;
                case '*' : return op1*op2;
                case '/' : return op1/op2;
                //default : return 0;
            }
        }
    };
       
    //solution 2 : using atoi / runtime 15 ms
     class Solution {
        public:
            int evalRPN(vector<string> &tokens) {
                stack<int> s;
                for (int i = 0; i < tokens.size(); ++i) {
                    int num = atoi(tokens[i].c_str());
                    if (num == 0 && (tokens[i][0] == '+' || tokens[i][0] == '-' || 
                    tokens[i][0] == '*' || tokens[i][0] == '/')) {
                        int op2 = s.top(); s.pop();
                        int op1 = s.top(); s.pop();
                        s.push(getResult(op1,op2,tokens[i][0]));
                    } else {
                       s.push(atoi(tokens[i].c_str())); 
                    }
                }
                return s.top();
            }
            
            inline int getResult(int op1, int op2, char op) {
                switch(op) {
                    case '+' : return op1 + op2;
                    case '-' : return op1-op2;
                    case '*' : return op1*op2;
                    case '/' : return op1/op2;
                }
            }
        };

  • 1
    W

    atoi exactly runs faster than stoi, about 28ms to 16ms in my code. Refer to the 85ms as you mentioned, I think it is the try-catch causes much time.


Log in to reply
 

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