具体解析看注释
#include<bits/stdc++.h>
using namespace std;
int priority(int x, char ch, int y)
{
switch (ch)
{
case '+':
return x + y;
break;
case '-':
return x - y;
break;
case '*':
return x * y;
break;
case '/':
return x / y;
break;
}
}
int first(char top, char ch)
{
if ((top == '+' || top == '-') && (ch == '+' || ch == '-')) return 1;
else if ((top == '*' || top == '/') && (ch == '*' || ch == '/')) return 1;
else if ((top == '*' || top == '/') && (ch == '+' || ch == '-')) return 1;
else if (ch == ')') return 0;
else return 2;
}
int main()
{
string s;
cin >> s;
stack<int> a;
stack<char>b;
int num=0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] >= '0' && s[i] <= '9')
{
if(num==0)
{
a.push(s[i]-'0');
num=1;
}
else
{
int Number=a.top();
a.pop();
Number= Number*10+(s[i]-'0');
a.push(Number);
}
}
else
{
num=0;
if (!b.empty())
{
int temp = first(b.top(), s[i]);
if (temp == 1)
{
int y = a.top();
a.pop();
int x = a.top();
a.pop();
int result = priority(x, b.top(), y);
b.pop();
b.push(s[i]);
a.push(result);
}
else if (temp == 2)
{
b.push(s[i]);
}
else if (temp == 0)
{
while (b.top() != '(')
{
b.top();
int y = a.top();
a.pop();
int x = a.top();
a.pop();
int result = priority(x, b.top(), y);
b.pop();
a.push(result);
}
b.pop();
}
}
else
{
b.push(s[i]);
}
}
}
while (!b.empty())
{
char C = b.top();
b.pop();
int y = a.top();
a.pop();
int x = a.top();
a.pop();
int result = priority(x, C, y);
a.push(result);
}
cout << a.top() << endl;
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)