# 227. 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.

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.

class Solution {
public:
int calculate(string s) {
stack<int> nums;
int cur=0;
char sign='+';
for(auto c:s)
{
if(isdigit(c))
cur=cur*10+(c-'0');
else if(c==' ')
continue;
else
{
if(sign=='+')
nums.push(cur);
else if(sign=='-')
nums.push(-cur);
else if(sign=='*')
nums.top()=nums.top()*cur;
else if(sign=='/')
nums.top()=nums.top()/cur;
sign=c;
cur=0;
}
}
if(sign=='+')
nums.push(cur);
else if(sign=='-')
nums.push(-cur);
else if(sign=='*')
nums.top()=nums.top()*cur;
else if(sign=='/')
nums.top()=nums.top()/cur;
int ans=0;
while(nums.size())
{
ans+=nums.top();
nums.pop();
}
return ans;
}
};

06-26 7582

09-15 7711
06-14 8884
05-29 3162
06-19 9237
05-23 3016
05-07 4541
09-14 3647
04-30 1785
06-04 13
05-23 3059
09-09 5036
08-13 1118
06-22 2340
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客