share my solution


  • 0
    Z
    class Solution {
    public:
        int calculate(string s) {
            // The evaluated part could always be expressed as a + b.
            // a + b + c = (a+b) + c
            // a + b - c = (a+b) + (-c)
            // a + b * c = a + (b*c)
            // a + b / c = a + (b/c)
            // is this easy to understand?
            int a =0; int b = 0;
            char op = '+';
            for(int i=0; i<s.size(); ++i) {
                if(s[i] == ' ') continue;
                if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
                    op = s[i];
                } else {
                    int val = 0;
                    int j= i;
                    while(j<s.size() && s[j] >= '0' && s[j] <= '9') ++j;
                    val = stoi(s.substr(i, j-i));
                    if (op == '+') {
                        a = a + b;
                        b = val;
                    } else if (op == '-') {
                        a = a + b;
                        b = -val;
                    } else if (op == '*') {
                        b = b * val;
                    } else {
                        b = b / val;
                    }
                    i = j-1;
                }
            }
            return a + b;
        }
    };
    

Log in to reply
 

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