后缀表达式
后缀表达式传送门
这个是所有识别表达式中最
水
的一个。每次加入一些元素, 如果碰到符号就把前俩进行运算, 然后搞进去, 继续。这样一个思路就可以想到可以用stack来解决这道水题。我这个人懒得手写,直接用STL了
大佬们不喜勿喷。
水洛谷时间 - 水代码
#include <bits/stdc++.h>
using namespace std;
string s;// string a str
inline int getans(string str) {// parameter is a str, take str to this funcitional(getans)
stack<int> s;//They're numbers
int size_s = str.size();
for (int i = 0; i < size_s; ++i) {
if (str[i] == ' ') continue;//' ' to continue because it is haven't something
else if (str[i] == '@') break;//if this is end('@) and break
else if (str[i] >= '0' && str[i] <= '9') {//if str[i] is a number
int sum = 0;//this number is zero
while (str[i] >= '0' && str[i] <= '9') {// if str[i] isn't a number->'.' and break to this while()
sum = (sum << 3) + (sum << 1) + (str[i] ^ 48); // = "sum = sum * 10 + str[i] - '0'"
++i;//point to next because this is went it!
}
s.push(sum);// push sum -> this number
continue;//else is nothing and leter of continue i is to next!
}
else if (str[i] == '-') {
int a = s.top(); s.pop();// take out top
int b = s.top(); s.pop();// take out top
// it is take out in front of the operator_tag's number and do something
s.push(b - a); // push b - a
//why is "b - a" not "a - b" ?
//because a is in front of the operator_tag, and b is in front of a, is in front of in front of the operator_tag
}
else if (str[i] == '+') {
int a = s.top(); s.pop();
int b = s.top(); s.pop();
s.push(a + b); // push a + b
//In addition, a + b = b + a
}
else if (str[i] == '*') {
int a = s.top(); s.pop();
int b = s.top(); s.pop();
s.push(a * b); // push a * b
//In multiplication, a * b = b * a
}
else if (str[i] == '/') {
int a = s.top(); s.pop();
int b = s.top(); s.pop();
s.push(b / a); // push b / a
}
}
return s.top();// Take out the calculated value
}
signed main() {
cin >> s; //input str
cout << getans(s) << endl;//output answer- number
return 0;
}