HW-OJ 计算器(根据输入表达式计算结果)
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <string>
#include <unordered_map>
#include <cmath>
class Solution {
private:
std::stack<int> values;
std::stack<char> operations;
std::unordered_map<char,int> oper_to_level;
public:
void init_map(){
oper_to_level.insert({'+',1});
oper_to_level.insert({'-',1});
oper_to_level.insert({'*',2});
oper_to_level.insert({'/',2});
oper_to_level.insert({'%',2});
oper_to_level.insert({'^',3});
}
void back_cal(std::stack<char>& operations, std::stack<int>& values){
if(operations.empty() || values.size() < 2) return;
int b = values.top(); values.pop();
char oper = operations.top(); operations.pop();
int a = values.top(); values.pop();
int res = match(a,b,oper);
values.push(res);
}
int match(int a, int b, char oper){
switch(oper){
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
case '%': return a % b;
case '^': return std::pow(a,b);
default: return 0;
}
}
std::string remove_space(std::string& str){
std::string result;
for(char ch : str){
if(ch != ' '){
result += ch;
}
}
return result;
}
int calculate(std::string s) {
init_map();
std::string str = remove_space(s);
str.pop_back();
for(int i = 0; i < str.length();){
if(str[i] == '('){
operations.push(str[i]);
i++;
}else if(str[i] == ')'){
while(!operations.empty() && operations.top() != '('){
back_cal(operations,values);
}
operations.pop();
i++;
}else if(std::isdigit(str[i])){
int val = 0;
while(std::isdigit(str[i]) && i < str.length()){
val = val * 10 + (str[i] - '0');
i++;
}
values.push(val);
}else{
while(!operations.empty()){
if(oper_to_level[operations.top()] >= oper_to_level[str[i]]){
back_cal(operations, values);
}else{
break;
}
}
operations.push(str[i]);
i++;
}
}
while(!operations.empty() && values.size() >= 2){
back_cal(operations, values);
}
return values.top();
}
};
int main(){
std::string str;
std::getline(std::cin, str);
Solution so;
int res = so.calculate(str);
std::cout << res << std::endl;
}