20ms C++, inspired by "Expression Add Operators"


  • 2
    C
    int calculate(string s) {
        char op = 0;
        int cur = 0;
        int prev = 0;
        int diff = 0;
        int i = 0;
        while (i < s.size()) {
            if (s[i] == ' ') {
                i++;
                continue;
            }
            if (isdigit(s[i])) {
                cur = 0;
                while (i < s.size() && isdigit(s[i])) {
                    cur = cur * 10 + s[i] - '0';
                    i++;
                }
                if (op == 0) {
                    prev = cur;
                    diff = cur;
                }
                else {
                    if (op == '+') {
                        diff = cur;
                        prev += cur;
                    }
                    else if (op == '-') {
                        diff = -cur;
                        prev -= cur;
                    }
                    else if (op == '*') {
                        int tmp = diff;
                        diff = diff * cur;
                        prev = prev - tmp + tmp * cur;
                    }
                    else if (op == '/') {
                        int tmp = diff;
                        diff = diff / cur;
                        prev = prev - tmp + tmp / cur;
                    }
                }
            }
            else {
                op = s[i];
                i++;
            }
        }
        return prev;
    }

Log in to reply
 

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