题解 | 四则运算
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
#include <iostream> #include <stack> #include <string> #include <cctype> using namespace std; void compute(stack<int>& st1, stack<char>& st2) { int b = st1.top(); st1.pop(); int a = st1.top(); st1.pop(); char op = st2.top(); st2.pop(); if ( op == '+') a = a + b; else if (op == '-') a = a - b; else if ( op == '*') a = a * b; else if (op == '/') a = a / b; st1.push(a); } bool priority(char m, char n) { if (m == '(') return false; else if (( m == '+' || m == '-') && ( n == '*' || n == '/')) return false; return true; } int main() { string s; while (cin >> s) { stack<int> st1; //记录运算数字 stack<char> st2; //记录运算符 st2.push('('); //整个运算式添加括号 s += ')'; bool flag = false; for (int i = 0; i < s.length(); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') //如果是左括号都在运算符栈加入( st2.push('('); else if (s[i] == ')' || s[i] == ']' || s[i] == '}') { //遇到右括号 while (st2.top() != '(') { //弹出开始计算直到遇到左括号 compute(st1, st2); } st2.pop(); //弹出左括号 } else if (flag) { while (priority(st2.top(), s[i])) { compute(st1, st2); } st2.push(s[i]); flag = false; } else { int j = i; if (s[j] == '-' || s[j] == '+') i++; while (isdigit(s[i])) i++; string temp = s.substr(j, i - j); st1.push(stoi(temp)); i--; flag = true; } } cout << st1.top() << endl; } return 0; }