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
分析:
数据结构与算法书中有利用栈实现更复杂计算器的例子。我试了下,感觉还是向量好用,可正向可逆向。
主要思路,分符号和数字两个容器。从前到后,是数字就计算,不是数字就开始判断。
当符号容器最后一个为*或/时,把数字容器中的数弹出来与当前数字做乘法或除法。同时记得把符号容器弹出最后一个符号(*或/),也要记得把当前的非数字(即符号压入容器我一直在这忘了耽搁好久。其他情况则将符号和数字分别都压入各自容器。
代码:
class Solution {
public:
int calculate(string s) {
s+="+";
vector<char> f;
vector<int> num;
int temp=0;
for(int i=0;i<s.size();++i)
{
if(s[i]==' ') continue;
if('0'<=s[i] && s[i]<='9')
{
temp=temp*10+(s[i]-'0');
}
else
{
if(!f.empty() && (f[f.size()-1]=='*' || f[f.size()-1]=='/'))
{
int m1=num[num.size()-1];
num.pop_back();
if(f[f.size()-1]=='*') num.push_back(m1*temp);
else if(f[f.size()-1]=='/') {num.push_back(m1/temp);}
f.pop_back();
f.push_back(s[i]);
}
else
{
num.push_back(temp);
f.push_back(s[i]);
}
temp=0;
}
}
f.pop_back();
int result=num[0];
for(int i=0,j=1;i<f.size();++i)
{
if(f[i]=='+') result+=num[j++];
else if(f[i]=='-') result-=num[j++];
}
return result;
}
};