227. Basic Calculator II

Problem:

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.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

Solutions:

class Solution {
public:
    int calculate(string s) {
        int sum = 0;
        int val = 0;
        char lastChar = '+';
        vector<int> v;
        for (int i = 0; i <= s.length(); ++i) {
            if (i != s.length()) {
                if (s[i] == ' ') {
                    continue;
                }
                if (isdigit(s[i])) {
                    val = val * 10 + (s[i] - '0');
                    continue;
                }
            }

            switch(lastChar) {
                case '+': 
                    v.push_back(val);
                    break;
                case '-': 
                    v.push_back(-val);
                    break;
                case '*': 
                    v.back() *= val;
                    break;
                case '/': 
                    v.back() /= val;
                    break;
            }

            val = 0;
            if (i != s.length()) {
                lastChar = s[i];
            }
        }

        for (auto val : v) {
            sum += val;
        }

        return sum;
    }
};

results matching ""

    No results matching ""