帶括號的四則運算——華為OJ
阿新 • • 發佈:2019-02-18
題目:
輸入一個只包含個位數字的簡單四則運算表示式字串,計算該表示式的值
注: 1、表示式只含 +, -, *, /, (, ), 四則運算子
2、表示式數值只包含個位整數(0-9),且不會出現0作為除數的情況
3、要考慮加減乘除按通常四則運算規定的計算優先順序
4、除法用整數除法,即僅保留除法運算結果的整數部分。比如8/3=2。輸入表示式保證無0作為除數情況發生
5、輸入字串一定是符合題意合法的表示式,其中只包括數字字元和四則運算子字元,除此之外不含其它任何 字元,不會出現計算溢位情況
充分利用了STL的模板類:棧stack和佇列queue 還是最傳統的計算方式:先把中綴表示式轉換為字尾表示式,再按順序計算就很簡單了
#include<iostream>
#include<string>
#include<stack>
#include<queue>
using namespace std;
int main()
{
string a;
int i=0;
stack<char> s;
queue<char> q;
getline(cin,a);
/////////////////////////
s.push(a[1]);
q.push(a[0]);
for(i=2;i<a.size();i++)
{
if ((a[i]<='9')&&(a[i]>='0'))
q.push(a[i]);
else if((a[i]=='+')||(a[i]=='-'))
{
if((s.top()=='*')||(s.top()=='/'))
{
q.push(s.top());
s.pop();
}
s.push(a[i]);
}
else if ((a[i]=='*')||(a[i]=='/'))
s.push(a[i]);
else if(a[i]=='(')
s.push(a[i]);
else if(a[i]==')')
{
while(s.top()!='(')
{
q.push(s.top());
s.pop();
}
s.pop();
}
}
/////全部出棧////////////////
while(!s.empty())
{
q.push(s.top());
s.pop();
}
//開始計算字尾表示式
//需要用一個棧
stack<int> ans;
int x1,x2;
while(!q.empty())
{
if((q.front()<='9')&&(q.front()>='0'))
{
ans.push(q.front()-'0');
q.pop();
}
else if(q.front()=='+')
{
x2=ans.top();
ans.pop();
x1=ans.top();
ans.pop();
ans.push(x1+x2);
q.pop();
}
else if(q.front()=='-')
{
x2=ans.top();
ans.pop();
x1=ans.top();
ans.pop();
ans.push(x1-x2);
q.pop();
}
else if(q.front()=='*')
{
x2=ans.top();
ans.pop();
x1=ans.top();
ans.pop();
ans.push(x1*x2);
q.pop();
}
else if(q.front()=='/')
{
x2=ans.top();
ans.pop();
x1=ans.top();
ans.pop();
ans.push(x1/x2);
q.pop();
}
}
cout<<ans.top();
}