a017.
五則運算
| From: [101.9.113.150] |
發表日期
:
2023-06-08 10:25
#include <bits/stdc++.h>
using namespace std;
int sum(int a,string b,int c)
{
if(b=="+")
return(a+c);
else if(b=="-")
return(a-c);
else if(b=="*")
return(a*c);
else if(b=="/")
return(a/c);
else if(b=="%")
return(a%c);
}
int main() {
string s, c;
while(getline(cin, s)) {
stack <string> st;
vector <string> ans;
stringstream ss;
ss << s;
while(ss >> c) {
if(c == ")")
{
while(st.top() != "(")
{
ans.push_back(st.top());
st.pop();
}
st.pop();
}
else if(c == "(")
{
st.push("(");
}
else if(c == "*" || c == "/"||c=="%")
{
while(!st.empty() && (st.top() == "*" || st.top() == "/")||c=="%")
{
ans.push_back(st.top());
st.pop();
}
st.push(c);
}
else if(c == "+" || c == "-")
{
while(!st.empty() && (st.top() == "*" || st.top() == "/" || st.top() == "+" || st.top() == "-")) {
ans.push_back(st.top());
st.pop();
}
st.push(c);
}
else
{
ans.push_back(c);
}
}
while(!st.empty())
{
ans.push_back(st.top());
st.pop();
}
stack < int > skk;
stringstream sss;
cout<<ans.size()<<endl;
int num=0;
for(int i=0;i<ans.size();i++)
{
if(ans[i]=="+"||ans[i]=="-"||ans[i]=="*"||ans[i]=="/"||ans[i]=="%")
{
int fir=0,sec=0;
sec=skk.top();
skk.pop();
fir=skk.top();
skk.pop();
skk.push(sum(fir,ans[i],sec));
}
else
{
sss<<ans[i];
sss>>num;
skk.push(num);
}
}
cout<<skk.top()<<endl;
skk.pop();
}
}