LeetCode Basic Calculator II

DESCIRPTION

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

SOLUTION

class Solution {
public:
    int calculate(string s) {
        char last_op = '+';
        char op = '+';
        int len = s.size();
        int curval = 0;
        int sumval = 0;
        int val = 0;
        int idx = read_number(s, 0, curval);

        while (idx < len) {
            idx = read_operator(s, idx, op);
            idx = read_number(s, idx, val);
            if (op == '-' || op == '+') {
                sumval = last_op == '-' ? sumval - curval : sumval + curval;
                curval = val;
                last_op= op;
            } else if (op == '*' || op == '/') {
                curval = op == '*' ? curval * val : curval / val;
            } else {
                cout<<"error"<<endl;
            }
        }
        sumval = last_op == '-' ? sumval - curval : sumval + curval;
        return sumval;
    }
    
    int read_number(const string& s, int from, int& val) {
        int len = s.size();
        val = 0;
        from = skip_space(s, from);
        while(from < len && s[from] >= '0' && s[from] <= '9') {
                val = val * 10 + s[from++] - '0';
        }
        from = skip_space(s, from);
        return from;
    }
    
    int read_operator(const string& s, int from, char& op) {
        from = skip_space(s, from);
        if (from == s.size()) {
            return from;
        } else {
            op = s[from];
            return ++from;  
        }
        from = skip_space(s, from);
    }
    
    int skip_space(const string& s, int from) {
        int len = s.size();
        while (from < len && s[from] == ' ') {
            from++;
        }
        return from;
    }
};

写的还是有些烦,不过一次AC

你可能感兴趣的:(LeetCode)