题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
#include <cctype> #include <iostream> #include <stack> #include <string> #include <bits/stdc++.h> using namespace std; bool compare_prioriy(char m, char n){ if(((m == '*' || m == '/' || m == '+' || m == '-') && (n == '+' || n == '-')) || ((m == '*' || m == '/') && (n == '*' || n == '/'))) return true; else return false; } void compute(stack<float> &figure, stack<char> &operand){ if(!figure.empty() && !operand.empty()){ float y = figure.top(); figure.pop(); float x = figure.top(); figure.pop(); char ch = operand.top(); operand.pop(); int result; switch(ch){ case '+': result = x + y; break; case '-': result = x - y; break; case '*': result = x * y; break; case '/': result = x / y; break; default: break; } figure.push(result); } } int main() { stack<float> figure; stack<char> operand; string str; cin >> str; bool flag = false;//标记是运算符还是正负号 for(int i = 0 ; i < str.length(); i++){ if(str[i] == '(' || str[i] == '[' || str[i] == '{'){ operand.push('('); } else if(str[i] == ')' || str[i] == ']' || str[i] == '}'){ while(!operand.empty() && operand.top() != '('){ compute(figure, operand); } operand.pop(); } else if(!flag){ int j = i; if(str[j] == '+' || str[j] == '-'){ i++; } while(isdigit(str[i])){//多位数的情况 i++; } figure.push(stoi(str.substr(j, i-j))); i--; flag = true;//除括号外上一个字符是数字,则之后的+-会被当作运算符 } else{ //栈顶和当前字符都是运算符且栈顶运算符的优先级>=当前运算符的优先级时要先进行运算(连续两次减法或除法不能调换运算顺序) while(!operand.empty() && compare_prioriy(operand.top(), str[i])){ compute(figure, operand); } operand.push(str[i]); flag = false;//除括号外上一个字符是运算符,则下一个+-是正负号 } } //括号内算完之后栈里可能还有内容,从栈顶依次运算即可 while(!operand.empty()){ compute(figure, operand); } cout << figure.top() << endl; return 0; }