Basic Calculator II

Tags : string, leetcode, cpp, medium

Given a string s which represents an expression, evaluate this expression and return its value.

The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Examples #

Example 1:

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

Example 2:

Input: s = " 3/2 "
Output: 1

Example 3:

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

Constraints #

Solutions #

class Solution {
public:
    int calculate(string s) {
      if(size(s)==0) return 0; 
      int res = 0;
      int l = size(s);
      int c = 0, cb = 0;
      char sn = '+';
      for(int i=0; i<l; i++){
        char cc = s[i];
        if(isdigit(cc)) c = (c*10) + (cc - '0');
        if(!isdigit(cc) and !iswspace(cc) or i == l-1){
          if(sn == '+' or sn == '-'){
            res += cb;
            cb = (sn == '+') ? c : -c;
          }else if(sn == '*') cb = cb*c;
           else if(sn == '/') cb = cb/c;
           sn = cc;
           c = 0;
        }
      }
      res += cb;
      return res;
    }
};