My neat c++, no trick, easy and short!


  • 0
    P
    int calculate(string s) {
        s += '+';
        int cur = 0, last = 1, ans = 0;
        bool pos = true, mul = true;
        for (char c: s)
            if (isdigit(c)) {
                cur = cur*10 + c-'0';
            } else if (c == '+' || c == '-') {
                ans += (mul ? last * cur : last / cur) * (pos ? 1 : -1);
                pos = c == '+', mul = true, last = 1, cur = 0;
            } else if (c == '*' || c == '/') {
                last = mul ? last * cur : last / cur;
                mul = c == '*', cur = 0;
            }
        return ans;
    }

Log in to reply
 

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