HDU 1237 简单计算器(栈+stringstream)

时间:2023-03-09 13:28:53
HDU 1237 简单计算器(栈+stringstream)

提供几份代码,这题的输入可以用stringsteam处理,先处理乘除后处理加减,正常思路,但是后面统计加减法的时候,对栈的运用错了,我用的时候相当于给它多加了几个括号就错了。

正确的简单解法就是,加法,就让正数入栈,减法就让该数的相反数入栈,之后的操作也不会影响该数的正负,这样处理最简单。

单栈

#include <iostream>
#include <sstream>
#include <stack>
using namespace std; stack<double> stn; int main()
{
string line;
while (getline(cin,line)) {
while (!stn.empty()) {
stn.pop();
}
if (line=="0") {
break;
} stringstream ss(line);
long long x;
string oper; ss>>x;
stn.push((double)x);
while (ss>>oper>>x) {
//cout<<oper<<endl<<x<<endl;
if (oper=="*") {
double num=stn.top();
stn.pop();
stn.push(num*(double)x);
}
else if (oper=="/") {
double num=stn.top();
stn.pop();
stn.push(num/(double)x);
}
else if (oper=="-") {
stn.push((double)-x);
}
else {
stn.push((double)x);
} }
double sum=0;
while (!stn.empty()) {
sum+=stn.top();
stn.pop();
}
printf("%.2lf\n",sum);
}
return 0;
}

双栈

AC

#include <iostream>
#include <sstream>
#include <stack>
using namespace std; stack<string> sts;
stack<double> stn; int main()
{
string line;
while (getline(cin,line)) {
while (!stn.empty()) {
stn.pop();
}
while (!sts.empty()) {
sts.pop();
}
if (line=="0") {
break;
} stringstream ss(line);
long long x;
string oper; ss>>x;
double sum=0;
stn.push(x);
while (ss>>oper>>x) {
//cout<<oper<<endl<<x<<endl;
if (oper=="*") {
double num=stn.top();
stn.pop();
stn.push(num*(double)x);
}
else if (oper=="/") {
double num=stn.top();
stn.pop();
stn.push(num/(double)x);
}
else {
stn.push((double)x);
sts.push(oper);
} }
while (!sts.empty()) {
string op=sts.top();
sts.pop();
if (op=="+") {
sum+=stn.top();
}
else {
sum-=stn.top();
}
stn.pop();
}
sum+=stn.top();
printf("%.2lf\n",sum);
}
return 0;
}

WA D了好久…

#include <iostream>
#include <sstream>
#include <stack>
using namespace std; stack<string> sts;
stack<double> stn; int main()
{
string line;
while (getline(cin,line)) {
while (!stn.empty()) {
stn.pop();
}
while (!sts.empty()) {
sts.pop();
} stringstream ss(line);
long long x;
string oper; ss>>x;
if (x==0&&line.length()==1) {
break;
}
stn.push((double)x);
while (ss>>oper>>x) {
//cout<<oper<<endl<<x<<endl;
if (oper=="*") {
double num=stn.top();
stn.pop();
stn.push(num*(double)x);
}
else if (oper=="/") {
double num=stn.top();
stn.pop();
stn.push(num/(double)x);
}
else {
stn.push((double)x);
sts.push(oper);
} }
while (!sts.empty()) {
string op=sts.top();
sts.pop();
double num2=stn.top();
stn.pop();
double num1=stn.top();
stn.pop();
if (op=="+") {
stn.push(num1+num2);
}
else {
stn.push(num1-num2);
}
}
printf("%.2lf\n",stn.top());
}
return 0;
}