← All problems

227. Basic Calculator II

MediumOpen on LeetCodeProblem statement

Problem Statement

227. Basic Calculator II

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 [-231, 231 - 1].

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

 

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:

C++

Source file
class Solution {
public:
int calculate(string s) {
        int n = s.size();
        stack<int> stk;
        char op='+';long num=0;
        for(int i=0;i<n;i++)
        {
            if(isdigit(s[i])) //s[i]>='0' && s[i]<='9'
                num=num*10 + (s[i]-'0');

            if((!isdigit(s[i])&& !isspace(s[i])) || i==n-1)
            {
                if(op=='+')
                {
                    stk.push(num);
                }
                else if(op=='-')
                {
                    stk.push(-num);
                }
                else if(op=='*')
                {
                    int top=stk.top();stk.pop();
                    num=top*num;
                    stk.push(num);
                }
                else
                {
                    int top=stk.top();
                    stk.pop();
                    num=top/num;
                    stk.push(num);
                }
                op=s[i];num=0;
            }
        }
        int res=0;
        while(!stk.empty()){
            res+=stk.top();
            stk.pop();
        }
        return res;
    }
};