定义两个栈,一个a栈用来存放数字,另一个b栈用来存放运算符,遇见数字将数字压入a栈,遇见运算符将运算符压入b栈,当第二次压入运算符之前? ?先与此时b栈栈顶的运算符'x'? ? 优先级进行比较,如果'x'优先级大于栈顶优先级,将'x'压栈,若小于,取出a栈中的栈顶元素a[top]和a[top-1]与b栈中栈顶运算符 'y' 进行运算,将运算结果result再次压入a的栈顶,将b栈顶运算符'y'弹出,将'x'运算符插入栈中。
当循环遍历完之后,可能栈中可能还会有剩余的运算符和整数没有运算,判断是否还有运算符,若有继续运算,没有则结束。
?
?
?
?
#include <iostream>
#include<cstring>
#include<stack>
using namespace std;
int compare(char front,char rear){//定义比较优先级函数,只需判断小于等于和大于
if((front=='+'&&rear=='+')||(front=='-'&&rear=='-')||(front=='*'&&rear=='*')||(front=='/'&&rear=='/')||(front=='+'&&rear=='*')||(front=='-'&&rear=='*')||(front=='+'&&rear=='/')||(front=='-'&&rear=='/')||(front=='/'&&rear=='*')||(front=='*'&&rear=='/')||(front=='+'&&rear=='-')||(front=='-'&&rear=='+'))
{
return 1;
}
else{
return 0;
}
}
int main() {
string s1;
cin >> s1;
stack<long long int> a;
stack<char> b;
double result;
for (int i = 0; i < s1.length(); i++) {
if (isdigit(s1[i])) {
long long int integer=0;
while(1){//数字不一定只有一位数
integer=integer*10+(s1[i]-'0');
if(isdigit(s1[i+1])==0)
{
break;
}
i++;
}
integer=integer%10000;
a.push(integer);
} else{
if(b.empty())
{
b.push(s1[i]);
}
else if (compare(s1[i],b.top())==1) {
int one, two;
one = a.top();
a.pop();
two = a.top();
a.pop();
if (b.top() == '+') result = two + one;
if (b.top() == '-') result = two - one;
if (b.top() == '*') result = ((two%10000) * (one%10000))%10000;
if (b.top() == '/') result = two / one;
b.pop();
b.push(s1[i]);
a.push(result);
} else if (compare(s1[i],b.top())==0) {
b.push(s1[i]);
}
}
}
while (!b.empty())//上面循环遍历完之后运算符有剩余则将栈中的运算符和数字进行运算,直到没有运算符
{
int a1,a2;
a1 = a.top();
a.pop();
a2 = a.top();
a.pop();
if (b.top() == '+') result = a1 + a2;
if (b.top() == '-') result = a1 - a2;
if (b.top() == '*') result = a1 * a2;
if (b.top() == '/') result = a1 / a2;
a.push(result);
b.pop();
}
cout<<a.top()%10000<<endl;//只留后四位
return 0;
}
[NOIP2013]表达式求值 - 题库 - 计蒜客
本来只是自己写写简单的运算表达式,写完之后找到这个题提交了一下(碰巧多刷一道题)
题解通过这个题目
|