Saturday, August 15, 2015

[LeetCode] Basic Calculator II

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
Note: Do not use the eval built-in library function.
Note: What can be done through stl stack, can also be done through stl vector.
class Solution {

public:
    int calculate(string s) {
        vector<int> numbers;
        vector<char> operators;
        int i = 0;
        while(i<s.length())
        {
            char e = s[i++];
            if(e == ' ') continue;
            
            if(isdigit(e))
            {
                int j = i;
                while(j < s.length() && isdigit(s[j]) ) j++;
                int num = stoi(s.substr(i-1, j-i+1));
                i = j;
                if(!operators.empty() && 
                    (operators.back() == '*' 
                    || operators.back() == '/')
                  )
                {
                    char op = operators.back();
                    operators.pop_back();
                    if(op == '*') numbers.back() *= num;
                    else numbers.back() /= num;
                }
                else numbers.push_back(num);
                
            }
            else operators.push_back(e);
        }
        
        if(numbers.empty()) return 0;
        int a = numbers[0];
        int opIndex = 0;
        for(int i = 1;i<numbers.size();i++)
        {
            char op = operators[opIndex++];
            if(op == '+') a += numbers[i];
            else a -= numbers[i];
        }
        return a;
    }
};