C++ 16ms 13 lines using istringstream, and 33ms 20 lines using self-implemented getNext()


  • 0

    16ms 13 lines using istringstream:

    int calculate(string s) {
            istringstream iss(s);
            int a = 0, b = 0, c = 0;    // a is the latest sum, b is the candidate to be added to a, c is next b
            iss >> b;                   // extract the first number
            
            for (char opC; (iss >> opC) && (iss >> c);) {
                if (opC == '+' || opC == '-') {
                    a += b, b = c * (opC == '+' ? 1 : -1);      // merge a and b, and update b
                } else if (opC == '*') {
                    b *= c;                                     // update b
                } else if (opC == '/') {
                    b /= c;                                     // update b
                }
            }
            
            return a + b;
    }
    

    33ms 20 lines using self-implemented getNext():

    class Solution {
    private:
        string getNext(string& s, int& pos) {
            while (pos < s.length() && s[pos] == ' ') { pos++; }    // skip initial spaces
            if (pos == s.length()) { return ""; }                   // no more valid element in s, return empty string
            if (!isdigit(s[pos])) { return s.substr(pos++, 1); }    // '+', '-', '*', '/'
            int start = pos;
            while (pos < s.length() && isdigit(s[pos])) { pos++; }  // get the number substring
            return s.substr(start, pos - start);
        }
        
    public:
        int calculate(string s) {
            int pos = 0, a = 0, b = stoi(getNext(s, pos));          // a is the latest sum, b is the candidate to be added to a
            
            while (pos < s.length()) {
                string signStr = getNext(s, pos), numStr = getNext(s, pos); // extract both sign substring and number substring
                
                if (signStr == "+" || signStr == "-") {
                    a += b, b = stoi(numStr) * (signStr == "+" ? 1 : -1);   // merge a and b, and update b
                } else if (signStr == "*") {
                    b *= stoi(numStr);                                      // update b
                } else if (signStr == "/") {
                    b /= stoi(numStr);                                      // update b
                }
            }
            
            return a + b;
        }
    };
    

Log in to reply
 

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